package com.mzj.saas.mservice.pay.service;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.haixiaoke.saas.repository.service.IOrderService;
import com.haixiaoke.saas.repository.service.ISubscribeService;
import com.haixiaoke.saas.repository.vo.SubscribeVo;
import com.mzj.saas.commons.Constant;
import com.mzj.saas.commons.DateUtils;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.enums.*;
import com.mzj.saas.commons.util.DataUtils;
import com.mzj.saas.mservice.backlog.entity.*;
import com.mzj.saas.mservice.backlog.repository.*;
import com.mzj.saas.mservice.backlog.vo.BacklogItemRedisVo;
import com.mzj.saas.mservice.bill.entity.*;
import com.mzj.saas.mservice.bill.repository.*;
import com.mzj.saas.mservice.bill.vo.PaymentBillRedisVo;
import com.mzj.saas.mservice.contract.entity.Contract;
import com.mzj.saas.mservice.contract.repository.ContractRepository;
import com.mzj.saas.mservice.department.entity.UserDepartmentRef;
import com.mzj.saas.mservice.department.repository.UserDepartmentRefRepository;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.house.repository.LockFrozenRepository;
import com.mzj.saas.mservice.lock.Repository.*;
import com.mzj.saas.mservice.lock.entity.*;
import com.mzj.saas.mservice.lock.service.LockAppService;
import com.mzj.saas.mservice.lockManager.entity.SmartLockBrand;
import com.mzj.saas.mservice.lockManager.repository.SmartLockBrandRepository;
import com.mzj.saas.mservice.pay.entity.EstateWxPay;
import com.mzj.saas.mservice.pay.entity.SaasHouseWxPay;
import com.mzj.saas.mservice.pay.entity.SaasRepairsWxPay;
import com.mzj.saas.mservice.pay.repository.EstateWxPayRepository;
import com.mzj.saas.mservice.pay.repository.SaasHouseWxPayRepository;
import com.mzj.saas.mservice.pay.repository.SaasRepairsWxPayRepository;
import com.mzj.saas.mservice.pay.vo.PaymentVo;
import com.mzj.saas.mservice.property.common.RepairsStatusEnum;
import com.mzj.saas.mservice.property.entity.*;
import com.mzj.saas.mservice.property.repository.*;
import com.mzj.saas.mservice.property.vo.RepairsPaymentRedisVo;
import com.mzj.saas.mservice.propertybill.entity.EstateViolateBill;
import com.mzj.saas.mservice.propertybill.repository.EstateViolateBillRepository;
import com.mzj.saas.mservice.propertybill.service.WithDrawService;
import com.mzj.saas.mservice.smartlock.service.SmartLockBrandService;
import com.mzj.saas.mservice.smartlock.service.ruanku.SmartLockCallBackService;
import com.mzj.saas.mservice.smartlock.vo.SmartLockVO;
import com.mzj.saas.mservice.smartlock.vo.yaluete.YltAuthorizationVO;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.redis.RedisService;
import com.mzj.saas.sdk.pay.callback.WxPayCallback;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 微信
 *
 * @author hp
 */
@Service
public class WxPayService {

    private Logger LOG = LoggerFactory.getLogger(WxPayService.class);
    @Autowired
    private RedisService redisService;
    @Autowired
    private SaasHouseWxPayRepository saasHouseWxPayRepository;
    @Autowired
    private EstateWxPayRepository estateWxPayRepository;
    @Autowired
    private RentBillRepository rentBillRepository;
    @Autowired
    private ExpenseBillRepository expenseBillRepository;
    @Autowired
    private HousePaymentOrderRepository housePaymentOrderRepository;
    @Autowired
    private EstatePaymentOrderRepository estatePaymentOrderRepository;
    @Autowired
    private AliPayService aliPayService;
    @Autowired
    private HousePaymentOrderRelationRepository housePaymentOrderRelationRepository;
    @Autowired
    private EstatePaymentOrderRelationRepository estatePaymentOrderRelationRepository;
    @Autowired
    private RentBillRelationRepository rentBillRelationRepository;
    @Autowired
    private EstateRentBillRepository estateRentBillRepository;
    @Autowired
    private EstateExpenseBillRepository estateExpenseBillRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private ContractRepository contractRepository;
    @Autowired
    private EstateRepairsRecordRepository estateRepairsRecordRepository;
    @Autowired
    private RepairsPaymentOrderRepository repairsPaymentOrderRepository;
    @Autowired
    private SaasRepairsWxPayRepository saasRepairsWxPayRepository;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private BacklogItemLockRepository backlogItemLockRepository;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private SmartLockCallBackService smartLockCallBackService;
    @Autowired
    private BacklogItemContractBillRepository backlogItemContractBillRepository;
    @Autowired
    private BacklogItemRecordSubmitRepository backlogItemRecordSubmitRepository;
    @Autowired
    private WithDrawService withDrawService;
    @Autowired
    private BacklogItemPropertyRentBillRepository backlogItemPropertyRentBillRepository;
    @Autowired
    private BacklogItemPropertyOtherBillRepository backlogItemPropertyOtherBillRepository;
    @Autowired
    private BacklogItemHouseOtherBillRepository backlogItemHouseOtherBillRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private HouseRemainingRepository houseRemainingRepository;
    @Autowired
    private HouseRemainingRecordRepository houseRemainingRecordRepository;
    @Autowired
    private CommunityHouseUserRepository communityHouseUserRepository;
    @Autowired
    private EstateViolateBillRepository estateViolateBillRepository;
    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private DepartmentBillRepository departmentBillRepository;
    @Autowired
    private BacklogItemHouseRemainingRepository backlogItemHouseRemainingRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private SmartLockBleRepository smartLockBleRepository;
    @Autowired
    private SmartLockPwdRepository smartLockPwdRepository;
    @Autowired
    private SmartLockCardRepository smartLockCardRepository;
    @Autowired
    private SmartLockFingerprintRepository smartLockFingerprintRepository;
    @Autowired
    private SmartLockFaceRepository smartLockFaceRepository;

    @Autowired
    private LockFrozenRepository lockFrozenRepository;
    @Autowired
    private SmartLockBrandService smartLockBrandService;
    @Autowired
    private SmartLockBrandRepository smartLockBrandRepository;
    @Autowired
    private HouseLockFrozenLogRepository houseLockFrozenLogRepository;
    @Autowired
    private LockAppService lockAppService;
    @Autowired
    private UserDepartmentRefRepository userDepartmentRefRepository;
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ISubscribeService subscribeService;



    /**
     * 微信app支付后端回调通知
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void appPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {

        LOG.info("WxPayService appPayCallback<微信app支付回调>");
        WxPayCallback callBack = new WxPayCallback(null, request, response);
        try {
            Map<String, String> result = callBack.verifyResult();
            if (result == null) {
                callBack.resultFail();
                return;
            }

            String attach = result.get("attach");
            if (StringUtils.isBlank(attach)) {
                LOG.error("WxPayService appPayCallback<微信app支付回调> attach is null");
                callBack.resultFail();
                return;
            }
            LOG.info("WxPayService appPayCallback<微信app支付回调> result={},params={}", result, attach);
            String outTradeNo = result.get("outTradeNo");
            PaymentVo paymentVo = redisService.getPaymentOrder(outTradeNo, PaymentVo.class);
            if (paymentVo == null) {
                LOG.error("WxPayService appPayCallback<微信app支付回调> 未找到预支付订单 outTradeNo={}", outTradeNo);
                callBack.resultSuccess();
                return;
            }

            if (paymentVo.getPaymentStatus() == 1) {
                LOG.info("WxPayService appPayCallback<微信app支付回调> 已支付成功 outTradeNo={}", outTradeNo);
                callBack.resultSuccess();
                return;
            }

            // 签名验证
            if (!callBack.verifySignature(paymentVo.getMchApiKey())) {
                callBack.resultFail();
                return;
            }
            Integer totalAmount = Integer.parseInt((result.get("totalFee")));

            Integer pAmount = DataUtils.doubleToInteger(paymentVo.getTotalAmount().doubleValue());
            if (totalAmount.intValue() != pAmount.intValue()) {
                LOG.error("WxPayService appPayCallback<微信app支付回调> 支付金额不匹配 outTradeNo={},totalAmount={},cost={}",
                        outTradeNo, DataUtils.IntegerToBigdecimal(totalAmount), paymentVo.getTotalAmount());
                callBack.resultFail();
                return;
            }

            // 公租房费用管理-账单
            if (paymentVo.getBusinessType() == 1) {
                handleBill(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 2) {
                // 报修费用
                handleRepairs(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 3) {
                // 待办事项
                handleBacklog(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 4) {
                // 物业房产租金/押金
                houseHandleBill(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 5) {
                // 生活缴费
                handleLifePay(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 6) {
                // 公租房其它费用
                otherHandleBill(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 7) {
                // 物业房产其它费用
                otherEstateHandleBill(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 8) {
                // 一体机扫码支付
                handleAioScanPay(outTradeNo, result, totalAmount);
            } else {
                LOG.warn("WxPayService appPayCallback<微信app支付回调>, 未匹配支付业务类型, businessType={}, outTradeNo={}",
                        paymentVo.getBusinessType(), outTradeNo);
            }
        } catch (Exception e) {
            LOG.error("微信app支付回调异常" + e.getMessage(), e);
            callBack.resultFail();
        }
        callBack.resultSuccess();
    }

    /**
     * 微信小程序支付后端回调通知
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void appletPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {

        LOG.info("WxPayService appletPayCallback<微信app支付回调>");
        WxPayCallback callBack = new WxPayCallback(null, request, response);
        try {
            Map<String, String> result = callBack.verifyResult();
            if (result == null) {
                callBack.resultFail();
                return;
            }

            String attach = result.get("attach");
            if (StringUtils.isBlank(attach)) {
                LOG.error("WxPayService appletPayCallback<微信小程序支付回调> attach is null");
                callBack.resultFail();
                return;
            }
            LOG.info("WxPayService appletPayCallback<微信小程序支付回调> result={},params={}", result, attach);
            String outTradeNo = result.get("outTradeNo");
            PaymentVo paymentVo = redisService.getPaymentOrder(outTradeNo, PaymentVo.class);
            if (paymentVo == null) {
                LOG.error("WxPayService appletPayCallback<微信小程序支付回调> 未找到预支付订单 outTradeNo={}", outTradeNo);
                callBack.resultSuccess();
                return;
            }

            if (paymentVo.getPaymentStatus() == 1) {
                LOG.info("WxPayService appletPayCallback<微信小程序支付回调> 已支付成功 outTradeNo={}", outTradeNo);
                callBack.resultSuccess();
                return;
            }

            // 签名验证
            if (!callBack.verifySignature(paymentVo.getMchApiKey())) {
                callBack.resultFail();
                return;
            }
            Integer totalAmount = Integer.parseInt((result.get("totalFee")));

            Integer pAmount = DataUtils.doubleToInteger(paymentVo.getTotalAmount().doubleValue());
            if (totalAmount.intValue() != pAmount.intValue()) {
                LOG.error("WxPayService appletPayCallback<微信小程序支付回调> 支付金额不匹配 outTradeNo={},totalAmount={},cost={}",
                        outTradeNo, DataUtils.IntegerToBigdecimal(totalAmount), paymentVo.getTotalAmount());
                callBack.resultFail();
                return;
            }

            // 公租房费用管理-账单
            if (paymentVo.getBusinessType() == 1) {
                handleBill(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 2) {
                // 报修费用
                handleRepairs(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 3) {
                // 待办事项
                handleBacklog(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 4) {
                // 物业房产租金/押金
                houseHandleBill(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 5) {
                // 生活缴费
                handleLifePay(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 6) {
                // 公租房其它费用
                otherHandleBill(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 7) {
                // 物业房产其它费用
                otherEstateHandleBill(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 8) {
                // 一体机扫码支付
                handleAioScanPay(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 12) {
                // 余额充值
                houseRemainingPay(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 13) {
                // 违约金支付
                houseViolateBillPay(outTradeNo, result, totalAmount);
            } else if (paymentVo.getBusinessType() == 15) {
                // 小程序账单支付
                billRemainingPay(outTradeNo, result, totalAmount);
            } else {
                LOG.warn("WxPayService appletPayCallback<微信小程序支付回调>, 未匹配支付业务类型, businessType={}, outTradeNo={}",
                        paymentVo.getBusinessType(), outTradeNo);
            }
        } catch (Exception e) {
            LOG.error("微信小程序支付回调异常" + e.getMessage(), e);
            callBack.resultFail();
        }
        callBack.resultSuccess();
    }


    private void billRemainingPay(String outTradeNo, Map<String, String> result, Integer totalAmount) {
        Date updateTime = new Date();
        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("WxPayService otherEstateHandleBill<微信小程序违约金支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);


        String userId = redisVo.getUserId();
        String operateName = userId;
        Optional<AppUser> byId = appUserRepository.findById(userId);
        if (byId.isPresent()) {
            if (StringUtils.isNotBlank(byId.get().getName())) {
                operateName = byId.get().getName();
            }
        } else {
            List<CommunityHouseUser> userId1 = communityHouseUserRepository.findByUserIdAndStatus(userId, 1);
            if (!CollectionUtils.isEmpty(userId1)) {
                operateName = userId1.get(0).getName();
            }
        }
        Date payTime = new Date();
        Long houseRemainingId = redisVo.getHouseRemainingId();
        // 保存操作记录
        HouseRemainingRecord vo = new HouseRemainingRecord();
        vo.setBillId(null);
        vo.setRemainingId(houseRemainingId);
        vo.setOperateMoney(totalAmount);
        vo.setOperatorId(userId);
        vo.setOperateName(operateName);
        vo.setLastUpdateTime(payTime);
        vo.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
        vo.setCause(PaymentCauseEnum.TOP_UP.getValue());
        vo.setOperateStatus(PaymentTypeEnum.TOP_UP.getValue());
        // 账单类型:1租金 2押金 3其他费用 4线上充值 5线下充值
        vo.setBillStatus(4);
        vo.setStatus(1);
        houseRemainingRecordRepository.save(vo);


        // 新增微信支付记录
        SaasHouseWxPay wxpay = new SaasHouseWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        saasHouseWxPayRepository.save(wxpay);

        List<Long> estateRentIds = redisVo.getEstateRentIds();
        List<Long> estateExpenseIds = redisVo.getEstateExpenseIds();

        List<EstateRentBill> rentBills = estateRentBillRepository.findByIdIn(estateRentIds);
        List<EstateExpenseBill> expenseBills = estateExpenseBillRepository.findByIdIn(estateExpenseIds);


        for (EstateExpenseBill estateExpenseBill : expenseBills) {
            Integer surplusCost = estateExpenseBill.getSurplusCost();
            estateExpenseBill.setSurplusCost(0);
            estateExpenseBill.setPaymentTime(updateTime);
            estateExpenseBill.setOperatorId(userId);
            estateExpenseBill.setPaymentChannel(PaymentTypeEnum.Remaining.getValue());
            estateExpenseBill.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            EstateExpenseBill saveBill = estateExpenseBillRepository.save(estateExpenseBill);


            // 余额操作记录
            HouseRemainingRecord record = new HouseRemainingRecord();
            record.setBillId(saveBill.getId());
            record.setRemainingId(houseRemainingId);
            record.setOperateMoney(surplusCost);
            record.setOperatorId(userId);
            record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
            record.setLastUpdateTime(updateTime);
            record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
            record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
            record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
            record.setBillStatus(PaymentTypeEnum.EXPENSE_BILL.getValue());
            // 状态：1正常 2已删除
            record.setStatus(1);
            houseRemainingRecordRepository.save(record);


            // 余额变动待办事项
            houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), houseRemainingId, estateExpenseBill.getChargeType(), surplusCost, userId, saveBill.getOrgId());
            // 其他费用待办事项
            propertyOtherItem(saveBill.getId());
        }
        for (EstateRentBill rentBill : rentBills) {
            Integer chargeType = rentBill.getChargeType();
            Integer surplusCost = rentBill.getSurplusCost();
            // 租金
            if (chargeType == 1) {
                rentBill.setSurplusCost(0);
                rentBill.setPaymentTime(updateTime);
                rentBill.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                EstateRentBill saveBill = estateRentBillRepository.save(rentBill);

                // 余额操作记录
                HouseRemainingRecord record = new HouseRemainingRecord();
                record.setBillId(saveBill.getId());
                record.setRemainingId(houseRemainingId);
                record.setOperateMoney(surplusCost);
                record.setOperatorId(userId);
                record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                record.setLastUpdateTime(updateTime);
                record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                record.setBillStatus(PaymentTypeEnum.RENT_BILL.getValue());
                // 状态：1正常 2已删除
                record.setStatus(1);
                houseRemainingRecordRepository.save(record);

                // 余额变动待办事项
                houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), houseRemainingId, chargeType, surplusCost, userId, saveBill.getOrgId());
                // 租金/押金待办事项
                propertyRentItem(saveBill.getId());
            } else {

                rentBill.setSurplusCost(0);
                rentBill.setPaymentTime(updateTime);
                rentBill.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                EstateRentBill saveBill = estateRentBillRepository.save(rentBill);


                HouseRemaining houseRemaining = houseRemainingRepository.findById(houseRemainingId).get();
                Integer cashPledge = houseRemaining.getCashPledge();
                houseRemaining.setCashPledge(cashPledge + surplusCost);
                houseRemaining.setLastUpdateTime(updateTime);
                houseRemainingRepository.save(houseRemaining);

                // 余额操作记录
                HouseRemainingRecord record = new HouseRemainingRecord();
                record.setBillId(saveBill.getId());
                record.setRemainingId(houseRemainingId);
                record.setOperateMoney(surplusCost);
                record.setOperatorId(userId);
                record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                record.setLastUpdateTime(updateTime);
                record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                record.setBillStatus(PaymentTypeEnum.DEPOSIT_BILL.getValue());
                // 状态：1正常 2已删除
                record.setStatus(1);
                houseRemainingRecordRepository.save(record);

                // 余额变动待办事项
                houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), houseRemainingId, chargeType, surplusCost, userId, saveBill.getOrgId());
                // 租金/押金待办事项
                propertyRentItem(saveBill.getId());
            }
        }
    }

    /**
     * 违约金支付
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     */
    @Transactional
    public void houseViolateBillPay(String outTradeNo, Map<String, String> result, Integer totalAmount) {
        LOG.info("WxPayService otherEstateHandleBill<微信小程序违约金支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("WxPayService otherEstateHandleBill<微信小程序违约金支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        List<EstateViolateBill> expenseBills = estateViolateBillRepository.findByIdIn(redisVo.getIds());
        if (CollectionUtils.isEmpty(expenseBills)) {
            LOG.error("WxPayService otherEstateHandleBill<微信小程序违约金支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }
        LOG.info("WxPayService otherEstateHandleBill, redisVo={}, expenseBills={}", JSON.toJSONString(redisVo),
                JSON.toJSONString(expenseBills));

        Date payTime = new Date();
        Integer billAmount = 0;

        List<EstatePaymentOrderRelation> porList = new ArrayList<>();
        for (EstateViolateBill b : expenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            por.setBusinessType(11);
            porList.add(por);
        }

        // 更新账单明细支付状态
        estateViolateBillRepository.saveAll(expenseBills);
        estatePaymentOrderRelationRepository.saveAll(porList);

        // 物业其他费用待办事项
        propertyOtherItem(redisVo.getIds());

        // 新增账单支付记录
        EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
        paymentOrder.setBillAmount(billAmount);
        paymentOrder.setOrderNumber(outTradeNo);
        paymentOrder.setPayType(2);
        paymentOrder.setPayMode(redisVo.getPaymentMode());
        paymentOrder.setPayTime(payTime);
        paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
        // 手续费 千分之6
        Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        paymentOrder.setWxCommissionAmount(payHandlingFee);
        paymentOrder.setPayUserId(redisVo.getUserId());
        paymentOrder.setTotalAmount(totalAmount);
        paymentOrder.setPayResult(1);
        estatePaymentOrderRepository.save(paymentOrder);

        // 新增微信支付明细
        EstateWxPay wxpay = new EstateWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        estateWxPayRepository.save(wxpay);
    }

    @Transactional
    public void houseRemainingPay(String outTradeNo, Map<String, String> result, Integer totalAmount) {
        LOG.info("WxPayService houseRemainingPay<微信小程序余额充值> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("WxPayService houseRemainingPay<微信小程序微信小程序余额充值账单支付回调> 未找到余额账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }

        String userId = redisVo.getUserId();
        String operateName = userId;
        Optional<AppUser> byId = appUserRepository.findById(userId);
        if (byId.isPresent()) {
            if (StringUtils.isNotBlank(byId.get().getName())) {
                operateName = byId.get().getName();
            }
        } else {
            List<CommunityHouseUser> userId1 = communityHouseUserRepository.findByUserIdAndStatus(userId, 1);
            if (!CollectionUtils.isEmpty(userId1)) {
                operateName = userId1.get(0).getName();
            }
        }
        Date payTime = new Date();
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        // 保存余额
        HouseRemaining houseRemaining = houseRemainingRepository.findById(redisVo.getHouseRemainingId()).get();
        Integer balanceFee = houseRemaining.getBalanceFee();
        BigDecimal bigDecimal = new BigDecimal(balanceFee);
        BigDecimal data = bigDecimal.add(new BigDecimal(totalAmount));
        houseRemaining.setBalanceFee(data.intValue());
        houseRemaining.setLastUpdateTime(payTime);
        houseRemainingRepository.save(houseRemaining);

        // 保存操作记录
        HouseRemainingRecord vo = new HouseRemainingRecord();
        vo.setBillId(null);
        vo.setRemainingId(redisVo.getHouseRemainingId());
        vo.setOperateMoney(totalAmount);
        vo.setOperatorId(userId);
        vo.setOperateName(operateName);
        vo.setLastUpdateTime(payTime);
        vo.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
        vo.setCause(PaymentCauseEnum.TOP_UP.getValue());
        vo.setOperateStatus(PaymentTypeEnum.TOP_UP.getValue());
        // 账单类型:1租金 2押金 3其他费用 4线上充值 5线下充值
        vo.setBillStatus(4);
        vo.setStatus(1);
        houseRemainingRecordRepository.save(vo);


        // 新增微信支付记录
        SaasHouseWxPay wxpay = new SaasHouseWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        saasHouseWxPayRepository.save(wxpay);

        // 账单扣减事件
        billDeduction(houseRemaining);

    }

    public void billDeduction(HouseRemaining houseRemaining) {

        String houseId = houseRemaining.getHouseId();
        Long orgId = houseRemaining.getOrgId();
        Long id = houseRemaining.getId();


        // 判断该机构是否有优先扣费账单
        DepartmentBill departmentBill = departmentBillRepository.findByDepId(orgId);
        List<UserDepartmentRef> byDepId = userDepartmentRefRepository.findByDepId(orgId);
        List<String> userId = byDepId.stream().map(UserDepartmentRef::getUserId).collect(Collectors.toList());
        List<User> byIdInAndType = userRepository.findByIdInAndType(userId, Short.parseShort("1"));
        User user = byIdInAndType.get(0);

        if (departmentBill != null) {
            Integer billStatus = departmentBill.getBillStatus();
            remainingDeduction(houseRemaining, billStatus);
        }
        Optional<HouseRemaining> byId = houseRemainingRepository.findById(id);
        houseRemaining = byId.get();
        Integer balanceFee = houseRemaining.getBalanceFee();
        if (balanceFee <= 0) {
            return;
        }

        // 查询出账户对应的收款单位未缴费账单
        List<EstateExpenseBill> expenseBills = estateExpenseBillRepository.findByHouseIdAndOrgId(houseId, orgId);
        List<EstateRentBill> estateRentBills = estateRentBillRepository.findByHouseIdAndOrgId(houseId, orgId);
        List<Map<String, Object>> bills = new ArrayList<>();
        for (EstateExpenseBill expenseBill : expenseBills) {
            Map<String, Object> map = new HashMap<>();
            map.put("billId", expenseBill.getId());
            map.put("billStatus", expenseBill.getChargeType());
            map.put("billType", 1);
            map.put("billTime", expenseBill.getLastUpdateTime());
            bills.add(map);
        }

        for (EstateRentBill estateRentBill : estateRentBills) {
            Map<String, Object> map = new HashMap<>();
            map.put("billId", estateRentBill.getId());
            map.put("billStatus", estateRentBill.getChargeType());
            map.put("billType", 2);
            map.put("billTime", estateRentBill.getCreateTime());
            bills.add(map);
        }

        // 按照账单审核时间排序扣款
        bills.sort((o1, o2) -> {
            Date billTime1 = (Date) o1.get("billTime");
            Date billTime2 = (Date) o2.get("billTime");
            return billTime1.compareTo(billTime2);
        });

        // 扣减账单
        remainingDeduction(houseRemaining, bills);

        // 扣减账单完成后判断账户状态并解冻智能锁
        if (houseRemaining.getStatus().equals(7)) {
            boolean flag = true;

            List<HouseRemaining> byHouseId = houseRemainingRepository.findByHouseId(houseId);
            for (HouseRemaining remaining : byHouseId) {
                if (!remaining.getId().equals(houseRemaining.getId())) {
                    // 1正常 2已删除 3延期 4欠费 5已退租 6已退款 7已冻结
                    if (remaining.getStatus() == 7) {
                        flag = false;
                    }
                }
            }

            // 物业其他账单
            List<EstateExpenseBill> expenseBillList = estateExpenseBillRepository.findByAuditStatusAndPaymentStatusAndHouseIdAndOrgId(1, 0, houseId, houseRemaining.getOrgId());
            // 物业租金押金
            List<EstateRentBill> rentBillList = estateRentBillRepository.findByAuditStatusAndPaymentStatusAndHouseIdAndOrgId(1, 0, houseId, houseRemaining.getOrgId());

            if (expenseBillList.size() + rentBillList.size() == 0) {
                houseRemaining.setStatus(RemainingStatusEnum.NORMAL.getValue());
                if (flag) {
                    // 判断是否合租
                    List<SmartLockAuth> smartLockAuths = new ArrayList<>();
                    Optional<House> houseById = houseRepository.findById(houseId);
                    if (houseById.isPresent()) {
                        House house = houseById.get();
                        if (house.getHousemateId() != null) {
                            smartLockAuths = smartLockAuthRepository.findBySubHouseId(houseId);

                        } else {
                            smartLockAuths = smartLockAuthRepository.findByHouseId(houseId);
                        }
                    }
                    // 智能锁授权解冻
                    smartLockThaw(smartLockAuths, user.getId());

                }
                houseRemainingRepository.save(houseRemaining);
            }
        }

    }

    private void smartLockThaw(List<SmartLockAuth> smartLockAuths, String userId) {

        String reason = "账户已缴清，系统解冻";
        Date date = new Date();
        if (!smartLockAuths.isEmpty()) {
            for (SmartLockAuth smartLockAuth : smartLockAuths) {
                Long lockAuthId = smartLockAuth.getId();

                Optional<SmartLock> lockOptional = smartLockRepository.findById(smartLockAuth.getLockId());
                if (!lockOptional.isPresent()) {
                    break;
                }
                SmartLock smartLock = lockOptional.get();
                // 单用户授权冻结, 一次冻结密码、身份证、CPU、指纹
                SmartLockPwd pwd = smartLockPwdRepository.findByLockAuthId(lockAuthId);
                List<SmartLockCard> cards = smartLockCardRepository.findByLockAuthId(lockAuthId);
                List<SmartLockFingerprint> fingerprint = smartLockFingerprintRepository.findByLockAuthId(lockAuthId);
                SmartLockBle ble = smartLockBleRepository.findByLockAuthId(lockAuthId);
                SmartLockFace face = smartLockFaceRepository.findByLockAuthId(lockAuthId);
                if (pwd != null || !cards.isEmpty() || !fingerprint.isEmpty() || ble != null || face != null) {
                    // 新增冻结记录
                    String houseId = smartLock.getHouseId();
                    // String matchUserName = smartLock.getMatchUserName();
                    String communityName = smartLock.getCommunityName();
                    String buildName = smartLock.getBuildName();
                    String unitName = smartLock.getUnitName();
                    String roomNumber = smartLock.getRoomNumber();

                    LockFrozen lockFrozen = new LockFrozen();
                    lockFrozen.setType(0);
                    lockFrozen.setLockId(smartLockAuth.getLockId());
                    lockFrozen.setLockAuditId(lockAuthId);
                    lockFrozen.setHouseId(houseId);
                    lockFrozen.setMatchUserName(smartLockAuth.getUserName());
                    lockFrozen.setCommunityName(communityName);
                    lockFrozen.setBuildName(buildName);
                    lockFrozen.setUnitName(unitName);
                    lockFrozen.setRoomNumber(roomNumber);
                    lockFrozen.setOperationState(2);
                    lockFrozen.setOperationTime(date);
                    lockFrozen.setOperationId(userId);
                    if (StringUtils.isNotBlank(reason)) {
                        lockFrozen.setReason(reason);
                    }
                    LockFrozen frozenSave = lockFrozenRepository.save(lockFrozen);

                    // 冻结密码
                    if (pwd != null) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setIndex(pwd.getPwdIndex());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        Integer authType = pwd.getAuthType();
                        if (authType == 1 || authType == 2) {
                            smartLockVO.setAuthType(LockAuthTypeEnum.NORMAL_PASS.getValue());
                        } else if (authType == 3) {
                            smartLockVO.setAuthType(LockAuthTypeEnum.TIMES_PASS.getValue());
                            smartLockVO.setTimes(pwd.getTimes());
                        }
                        smartLockVO.setSuspend(0);// 0:解冻 1:冻结
                        smartLockVO.setLockFrozenId(frozenSave.getId());
                        smartLockVO.setIndexNum(pwd.getPwdIndexNum());
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            YltAuthorizationVO yltVO = new YltAuthorizationVO();
                            yltVO.setfLockMAC(smartLock.getMac());
                            yltVO.setfAppUserID(pwd.getfAppUserId());
                            yltVO.setfBeginDate(com.mzj.saas.commons.util.DateUtils.format(pwd.getStartTime(), com.mzj.saas.commons.util.DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfEndDate(com.mzj.saas.commons.util.DateUtils.format(pwd.getEndTime(), com.mzj.saas.commons.util.DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfOpenByPassword(1);
                            yltVO.setfOpenByIDCard(0);
                            yltVO.setfOpenByBLE(0);
                            yltVO.setfOpenByFinger(0);
                            yltVO.setfOpenByICCard(0);
                            yltVO.setfOpenPassword(pwd.getPassword());
                            smartLockVO.setYltAuth(yltVO);
                        }

                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreeze(smartLockVO,
                                smartLock.getBrandId(), XzLockOperatorTypeEnum.PWD.getValue());
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            // 失败，删除冻结记录
                            lockFrozenRepository.deleteById(frozenSave.getId());
                        } else {
                            // 冻结后默认待执行
                            pwd.setStatus(0);
                            smartLockPwdRepository.save(pwd);
                            // 亚略特
                            // if (smartLock.getBrandId() == 3L) {
                            lockAppService.yltUpdateStatus(pwd, null, null, null, null, 0, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                            //}
                        }
                    }

                    // 冻结卡
                    if (!cards.isEmpty()) {
                        for (SmartLockCard card : cards) {
                            SmartLockVO smartLockVO = new SmartLockVO();
                            smartLockVO.setSn(smartLock.getSn());
                            smartLockVO.setIndex(card.getCardIndex());
                            smartLockVO.setAuthInfoId(lockAuthId);
                            smartLockVO.setCardType(card.getType());
                            smartLockVO.setSuspend(0);// 0:解冻 1:冻结
                            smartLockVO.setLockFrozenId(frozenSave.getId());
                            smartLockVO.setIndexNum(card.getCardIndexNum());
                            // 亚略特
                            if (smartLock.getBrandId() == 3L) {
                                YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                yltVO.setfLockMAC(smartLock.getMac());
                                yltVO.setfAppUserID(card.getfAppUserId());
                                yltVO.setfBeginDate(com.mzj.saas.commons.util.DateUtils.format(card.getStartTime(), com.mzj.saas.commons.util.DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfEndDate(com.mzj.saas.commons.util.DateUtils.format(card.getEndTime(), com.mzj.saas.commons.util.DateUtils.FORMAT_DATETIME_14));
                                yltVO.setfOpenByPassword(0);
                                yltVO.setfOpenByBLE(0);
                                yltVO.setfOpenByFinger(0);
                                if (card.getType() == 1) {
                                    yltVO.setfOpenByIDCard(1);
                                    yltVO.setfOpenByICCard(0);
                                } else {
                                    yltVO.setfOpenByIDCard(0);
                                    yltVO.setfOpenByICCard(1);
                                }
                                yltVO.setfIDCardID(card.getCardId());
                                yltVO.setfIDCardNumber(card.getCardNumber());
                                smartLockVO.setYltAuth(yltVO);
                            }

                            ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeCard(smartLockVO,
                                    smartLock.getBrandId(), XzLockOperatorTypeEnum.CARD.getValue());
                            String msg = stringResultBean.getMsg();
                            String code = stringResultBean.getCode();
                            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                                // 失败，删除冻结记录
                                lockFrozenRepository.deleteById(frozenSave.getId());
                            } else {
                                // 冻结后默认待执行
                                card.setStatus(0);
                                smartLockCardRepository.save(card);
                                // 亚略特
                                // if (smartLock.getBrandId() == 3L) {
                                lockAppService.yltUpdateStatus(null, card, null, null, null, 0, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                                //}
                            }
                        }
                    }

                    // 指纹锁
                    if (!fingerprint.isEmpty()) {
                        Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(smartLock.getBrandId());
                        if (optional.isPresent()) {
                            SmartLockBrand brand = optional.get();
                            // 品牌支持指纹锁
                            if (brand.getFingerprintStatus() != null && brand.getFingerprintStatus() == 1) {
                                for (SmartLockFingerprint fg : fingerprint) {
                                    SmartLockVO smartLockVO = new SmartLockVO();
                                    smartLockVO.setSn(smartLock.getSn());
                                    smartLockVO.setIndex(fg.getFingerprintIndex());
                                    smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                    smartLockVO.setAuthInfoId(lockAuthId);
                                    smartLockVO.setSuspend(0);// 0:解冻 1:冻结
                                    smartLockVO.setLockFrozenId(frozenSave.getId());
                                    smartLockVO.setIndexNum(fg.getFingerprintIndexNum());
                                    // 亚略特
                                    if (smartLock.getBrandId() == 3L) {

                                        YltAuthorizationVO yltVO = new YltAuthorizationVO();
                                        yltVO.setfLockMAC(smartLock.getMac());
                                        yltVO.setfAppUserID(fg.getfAppUserId());
                                        yltVO.setfBeginDate(com.mzj.saas.commons.util.DateUtils.format(fg.getStartTime(), com.mzj.saas.commons.util.DateUtils.FORMAT_DATETIME_14));
                                        yltVO.setfEndDate(com.mzj.saas.commons.util.DateUtils.format(fg.getEndTime(), com.mzj.saas.commons.util.DateUtils.FORMAT_DATETIME_14));
                                        yltVO.setfOpenByPassword(0);
                                        yltVO.setfOpenByIDCard(0);
                                        yltVO.setfOpenByBLE(0);
                                        yltVO.setfOpenByFinger(1);
                                        yltVO.setfOpenByICCard(0);
                                        yltVO.setfFingerFeature(fg.getFingerprint());
                                        smartLockVO.setYltAuth(yltVO);

                                    }

                                    ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeFingerprint(
                                            smartLockVO, smartLock.getBrandId(), XzLockOperatorTypeEnum.FINGERPRINT.getValue());
                                    String msg = stringResultBean.getMsg();
                                    String code = stringResultBean.getCode();
                                    if (code != StatusCode.SUCCESS_CODE_10000.getErrorCode()) {
                                        // 失败，删除冻结记录
                                        lockFrozenRepository.deleteById(frozenSave.getId());
                                    } else {
                                        // 冻结后默认待执行
                                        fg.setStatus(0);
                                        smartLockFingerprintRepository.save(fg);
                                        // 亚略特
                                        // if (smartLock.getBrandId() == 3L) {
                                        lockAppService.yltUpdateStatus(null, null, fg, null, null, 0, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                                        //}
                                    }
                                }
                            }
                        }
                    }

                    // 蓝牙
                    if (ble != null) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        smartLockVO.setSuspend(0);// 0:解冻 1:冻结
                        smartLockVO.setLockFrozenId(frozenSave.getId());
                        // 亚略特
                        if (smartLock.getBrandId() == 3L) {
                            YltAuthorizationVO yltVO = new YltAuthorizationVO();
                            yltVO.setfLockMAC(smartLock.getMac());
                            yltVO.setfAppUserID(ble.getfAppUserId());
                            yltVO.setfBeginDate(com.mzj.saas.commons.util.DateUtils.format(ble.getStartTime(), com.mzj.saas.commons.util.DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfEndDate(com.mzj.saas.commons.util.DateUtils.format(ble.getEndTime(), com.mzj.saas.commons.util.DateUtils.FORMAT_DATETIME_14));
                            yltVO.setfOpenByPassword(0);
                            yltVO.setfOpenByIDCard(0);
                            yltVO.setfOpenByBLE(1);
                            yltVO.setfOpenByFinger(0);
                            yltVO.setfOpenByICCard(0);
                            smartLockVO.setYltAuth(yltVO);
                        }

                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeBle(smartLockVO, smartLock.getBrandId());
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            // 失败，删除冻结记录
                            lockFrozenRepository.deleteById(frozenSave.getId());
                        } else {
                            // 冻结后默认待执行
                            ble.setStatus(0);
                            smartLockBleRepository.save(ble);
                            // 亚略特
                            // if (smartLock.getBrandId() == 3L) {
                            lockAppService.yltUpdateStatus(null, null, null, ble, null, 0, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                            //}
                        }
                    }

                    // 人脸
                    if (face != null) {
                        SmartLockVO smartLockVO = new SmartLockVO();
                        smartLockVO.setSn(smartLock.getSn());
                        smartLockVO.setAuthInfoId(lockAuthId);
                        smartLockVO.setSuspend(0);// 0:解冻 1:冻结
                        smartLockVO.setLockFrozenId(frozenSave.getId());

                        face.setSn(smartLock.getSn());
                        ResultBean<String> stringResultBean = smartLockBrandService.freezeOrUnfreezeFace(smartLockVO, face, smartLock.getBrandId());
                        String resultData = stringResultBean.getResultData();
                        String msg = stringResultBean.getMsg();
                        String code = stringResultBean.getCode();
                        if (!code.equals(com.mzj.saas.commons.StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            // 失败，删除冻结记录
                            lockFrozenRepository.deleteById(frozenSave.getId());
                        } else {
                            if (StrUtil.isNotEmpty(resultData)) {
                                if (smartLock.getBrandId() == 8L) {
                                    String phoneNo = (String) JSONObject.parseObject(resultData).get("phoneNo");
                                    face.setIdentification(phoneNo);
                                    String keyId = (String) JSONObject.parseObject(resultData).get("keyId");
                                    face.setKeyId(keyId);
                                } else {
                                    face.setIdentification(resultData);
                                    face.setReturnFaceId(StrUtil.isEmpty(resultData) ? null : Long.valueOf(resultData));
                                }
                            }
                            // 冻结后默认待执行
                            face.setStatus(0);
                            smartLockFaceRepository.save(face);
                            // 亚略特
                            // if (smartLock.getBrandId() == 3L) {
                            lockAppService.yltUpdateStatus(null, null, null, null, face, 0, stringResultBean, smartLockAuth, lockFrozen, smartLock);
                            //}
                        }
                    }

                }

                //  写入冻结日志表
                HouseLockFrozenLog houseLockFrozenLog = new HouseLockFrozenLog();
                houseLockFrozenLog.setType(0);// 操作类型: 0:解冻 1:冻结
                houseLockFrozenLog.setLockId(smartLock.getId());// 智能锁绑定id
                houseLockFrozenLog.setHouseId(smartLock.getHouseId()); // 公租房id
                houseLockFrozenLog.setLockAuditId(lockAuthId); // 授权信息id
                houseLockFrozenLog.setOperationTime(new Date()); // 操作时间
                houseLockFrozenLog.setOperationId(userId); // 操作时间
                houseLockFrozenLog.setOperationState(2);
                houseLockFrozenLogRepository.save(houseLockFrozenLog);

                /**
                 * 产生智能锁冻结/解冻待办事项
                 */
                lockAppService.addBacklogItem(smartLockAuth.getMobile(), reason, 0, smartLock.getHouseId(), smartLockAuth.getAuthorUserId(), userId, null);
                // 更新亚略特智能锁状态
                lockAppService.yltUpdateLockStatus(smartLock, 0);
                // 更新锁授权人数
                lockAppService.updateOauthNumber(smartLock.getBrandId(), smartLockAuth.getLockId());
            }
        }

    }

    private void remainingDeduction(HouseRemaining houseRemaining, Integer billStatus) {
        Long orgId = houseRemaining.getOrgId();
        String houseId = houseRemaining.getHouseId();

        final Date updateTime = new Date();

        Integer operateMoney = 0;

        if (billStatus != null) {
            if (!billStatus.equals(8) && !billStatus.equals(9)) {
                List<EstateExpenseBill> expenseBills = estateExpenseBillRepository.findByHouseIdAndChargeTypeAndOrgId(houseId, billStatus, orgId);
                if (!CollectionUtils.isEmpty(expenseBills)) {
                    for (EstateExpenseBill expenseBill : expenseBills) {
                        Optional<HouseRemaining> byId = houseRemainingRepository.findById(houseRemaining.getId());
                        houseRemaining = byId.get();
                        Integer balanceFee = houseRemaining.getBalanceFee();

                        if (balanceFee <= 0) {
                            return;
                        }

                        Integer cost = expenseBill.getSurplusCost();
                        BigDecimal billCost = new BigDecimal(cost);
                        BigDecimal remaining = new BigDecimal(balanceFee);
                        if (balanceFee - cost <= 0) {// 部分缴费
                            operateMoney = balanceFee;

                            int paymentStatus = DeductionEnum.PART_PAY.getValue();
                            if (balanceFee - cost == 0) {
                                paymentStatus = DeductionEnum.ALL_PAY.getValue();
                            }
                            // 账单费用抵扣
                            cost = Integer.parseInt(billCost.subtract(remaining).toString());
                            expenseBill.setSurplusCost(cost);
                            expenseBill.setPaymentStatus(paymentStatus);
                            expenseBill.setPaymentTime(updateTime);
                            expenseBill.setPaymentChannel(PaymentTypeEnum.Remaining.getValue());
                            EstateExpenseBill saveBill = estateExpenseBillRepository.save(expenseBill);

                            // 余额扣减
                            houseRemaining.setBalanceFee(0);
                            houseRemaining.setLastUpdateTime(updateTime);
                            HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                            // 余额操作记录
                            HouseRemainingRecord record = new HouseRemainingRecord();
                            record.setBillId(saveBill.getId());
                            record.setRemainingId(saveRemaining.getId());
                            record.setOperateMoney(operateMoney);
                            record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                            record.setLastUpdateTime(updateTime);
                            record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                            record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                            record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                            record.setBillStatus(PaymentTypeEnum.EXPENSE_BILL.getValue());
                            // 状态：1正常 2已删除
                            record.setStatus(1);
                            houseRemainingRecordRepository.save(record);

                            // 余额变动待办事项
                            houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), billStatus, operateMoney, null, saveBill.getOrgId());
                        } else {
                            operateMoney = cost;
                            // 账单费用扣减
                            cost = Integer.parseInt(remaining.subtract(billCost).toString());
                            expenseBill.setSurplusCost(0);
                            expenseBill.setPaymentTime(updateTime);
                            expenseBill.setPaymentChannel(PaymentTypeEnum.Remaining.getValue());
                            expenseBill.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                            EstateExpenseBill saveBill = estateExpenseBillRepository.save(expenseBill);

                            // 余额扣减
                            houseRemaining.setBalanceFee(cost);
                            houseRemaining.setLastUpdateTime(updateTime);
                            HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                            // 余额操作记录
                            HouseRemainingRecord record = new HouseRemainingRecord();
                            record.setBillId(saveBill.getId());
                            record.setRemainingId(saveRemaining.getId());
                            record.setOperateMoney(operateMoney);
                            record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                            record.setLastUpdateTime(updateTime);
                            record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                            record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                            record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                            record.setBillStatus(PaymentTypeEnum.EXPENSE_BILL.getValue());
                            // 状态：1正常 2已删除
                            record.setStatus(1);
                            houseRemainingRecordRepository.save(record);


                            // 余额变动待办事项
                            houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), billStatus, operateMoney, null, saveBill.getOrgId());
                            // 其他费用待办事项
                            propertyOtherItem(saveBill.getId());

                        }
                    }
                }

            } else {
                List<EstateRentBill> expenseBills = estateRentBillRepository.findByHouseIdAndChargeTypeAndOrgId(houseId, billStatus.equals(8) ? 1 : 2, orgId);
                for (EstateRentBill estateRentBill : expenseBills) {

                    Optional<HouseRemaining> byId = houseRemainingRepository.findById(houseRemaining.getId());
                    houseRemaining = byId.get();
                    Integer balanceFee = houseRemaining.getBalanceFee();

                    if (balanceFee <= 0) {
                        return;
                    }

                    Integer rentBillChargeType = estateRentBill.getChargeType();
                    Integer cost = estateRentBill.getSurplusCost();
                    BigDecimal billCost = new BigDecimal(cost);
                    BigDecimal remaining = new BigDecimal(balanceFee);
                    if (rentBillChargeType == 1) {// 租金
                        if (balanceFee - cost <= 0) {
                            operateMoney = balanceFee;

                            int paymentStatus = DeductionEnum.PART_PAY.getValue();
                            if (balanceFee - cost == 0) {
                                paymentStatus = DeductionEnum.ALL_PAY.getValue();
                            }
                            // 账单费用抵扣
                            cost = Integer.parseInt(billCost.subtract(remaining).toString());
                            estateRentBill.setSurplusCost(cost);
                            estateRentBill.setPaymentStatus(paymentStatus);
                            estateRentBill.setPaymentTime(updateTime);
                            EstateRentBill saveBill = estateRentBillRepository.save(estateRentBill);

                            // 余额扣减
                            houseRemaining.setBalanceFee(0);
                            houseRemaining.setLastUpdateTime(updateTime);
                            HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                            // 余额操作记录
                            HouseRemainingRecord record = new HouseRemainingRecord();
                            record.setBillId(saveBill.getId());
                            record.setRemainingId(saveRemaining.getId());
                            record.setOperateMoney(operateMoney);
                            record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                            record.setLastUpdateTime(updateTime);
                            record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                            record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                            record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                            record.setBillStatus(PaymentTypeEnum.RENT_BILL.getValue());
                            // 状态：1正常 2已删除
                            record.setStatus(1);
                            houseRemainingRecordRepository.save(record);

                            // 余额变动待办事项
                            houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), billStatus, operateMoney, null, saveBill.getOrgId());
                        } else {
                            operateMoney = cost;
                            // 账单费用扣减
                            cost = Integer.parseInt(remaining.subtract(billCost).toString());
                            estateRentBill.setSurplusCost(0);
                            estateRentBill.setPaymentTime(updateTime);
                            estateRentBill.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                            EstateRentBill saveBill = estateRentBillRepository.save(estateRentBill);

                            // 余额扣减
                            houseRemaining.setBalanceFee(cost);
                            houseRemaining.setLastUpdateTime(updateTime);
                            HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                            // 余额操作记录
                            HouseRemainingRecord record = new HouseRemainingRecord();
                            record.setBillId(saveBill.getId());
                            record.setRemainingId(saveRemaining.getId());
                            record.setOperateMoney(operateMoney);
                            record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                            record.setLastUpdateTime(updateTime);
                            record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                            record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                            record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                            record.setBillStatus(PaymentTypeEnum.RENT_BILL.getValue());
                            // 状态：1正常 2已删除
                            record.setStatus(1);
                            houseRemainingRecordRepository.save(record);

                            // 余额变动待办事项
                            houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), billStatus, operateMoney, null, saveBill.getOrgId());
                            // 租金/押金待办事项
                            propertyRentItem(saveBill.getId());
                        }
                    } else {
                        // 押金
                        if (balanceFee - cost <= 0) {
                            operateMoney = balanceFee;

                            int paymentStatus = DeductionEnum.PART_PAY.getValue();
                            if (balanceFee - cost == 0) {
                                paymentStatus = DeductionEnum.ALL_PAY.getValue();
                            }
                            // 账单费用抵扣
                            cost = Integer.parseInt(billCost.subtract(remaining).toString());
                            estateRentBill.setSurplusCost(cost);
                            estateRentBill.setPaymentStatus(paymentStatus);
                            estateRentBill.setPaymentTime(updateTime);
                            EstateRentBill saveBill = estateRentBillRepository.save(estateRentBill);

                            // 余额扣减
                            houseRemaining.setBalanceFee(0);
                            houseRemaining.setCashPledge(operateMoney);
                            houseRemaining.setLastUpdateTime(updateTime);
                            HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                            // 余额操作记录
                            HouseRemainingRecord record = new HouseRemainingRecord();
                            record.setBillId(saveBill.getId());
                            record.setRemainingId(saveRemaining.getId());
                            record.setOperateMoney(operateMoney);
                            record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                            record.setLastUpdateTime(updateTime);
                            record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                            record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                            record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                            record.setBillStatus(PaymentTypeEnum.DEPOSIT_BILL.getValue());
                            // 状态：1正常 2已删除
                            record.setStatus(1);
                            houseRemainingRecordRepository.save(record);

                            // 余额变动待办事项
                            houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), billStatus, operateMoney, null, saveBill.getOrgId());
                        } else {
                            operateMoney = cost;
                            // 账单费用扣减
                            cost = Integer.parseInt(remaining.subtract(billCost).toString());
                            estateRentBill.setSurplusCost(0);
                            estateRentBill.setPaymentTime(updateTime);
                            estateRentBill.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                            EstateRentBill saveBill = estateRentBillRepository.save(estateRentBill);

                            // 余额扣减
                            houseRemaining.setBalanceFee(cost);
                            houseRemaining.setCashPledge(operateMoney);
                            houseRemaining.setLastUpdateTime(updateTime);
                            HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                            // 余额操作记录
                            HouseRemainingRecord record = new HouseRemainingRecord();
                            record.setBillId(saveBill.getId());
                            record.setRemainingId(saveRemaining.getId());
                            record.setOperateMoney(operateMoney);
                            record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                            record.setLastUpdateTime(updateTime);
                            record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                            record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                            record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                            record.setBillStatus(PaymentTypeEnum.DEPOSIT_BILL.getValue());
                            // 状态：1正常 2已删除
                            record.setStatus(1);
                            houseRemainingRecordRepository.save(record);

                            // 余额变动待办事项
                            houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), billStatus, operateMoney, null, saveBill.getOrgId());
                            // 租金/押金待办事项
                            propertyRentItem(saveBill.getId());
                        }
                    }
                }
            }
        }


    }


    private void remainingDeduction(HouseRemaining houseRemaining, List<Map<String, Object>> bills) {
        Date updateTime = new Date();
        for (Map<String, Object> bill : bills) {
            Integer operateMoney = 0;

            Long id = houseRemaining.getId();
            Optional<HouseRemaining> byId = houseRemainingRepository.findById(id);
            houseRemaining = byId.get();
            Integer balanceFee = houseRemaining.getBalanceFee();
            if (balanceFee <= 0) {
                return;
            }
            Integer type = Integer.parseInt(bill.get("billType").toString());
            // 1其他费用
            if (type.equals(1)) {
                Long billId = Long.parseLong(bill.get("billId").toString());
                Optional<EstateExpenseBill> expenseBillById = estateExpenseBillRepository.findById(billId);
                if (expenseBillById.isPresent()) {
                    EstateExpenseBill expenseBill = expenseBillById.get();

                    Integer cost = expenseBill.getSurplusCost();
                    BigDecimal billCost = new BigDecimal(cost);
                    BigDecimal remaining = new BigDecimal(balanceFee);
                    if (balanceFee - cost <= 0) {// 部分缴费
                        operateMoney = balanceFee;

                        int paymentStatus = DeductionEnum.PART_PAY.getValue();
                        if (balanceFee - cost == 0) {
                            paymentStatus = DeductionEnum.ALL_PAY.getValue();
                        }
                        // 账单费用抵扣
                        cost = Integer.parseInt(billCost.subtract(remaining).toString());
                        expenseBill.setSurplusCost(cost);
                        expenseBill.setPaymentStatus(paymentStatus);
                        expenseBill.setPaymentTime(updateTime);
                        expenseBill.setPaymentChannel(PaymentTypeEnum.Remaining.getValue());
                        EstateExpenseBill saveBill = estateExpenseBillRepository.save(expenseBill);

                        // 余额扣减
                        houseRemaining.setBalanceFee(0);
                        houseRemaining.setLastUpdateTime(updateTime);
                        HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                        // 余额操作记录
                        HouseRemainingRecord record = new HouseRemainingRecord();
                        record.setBillId(saveBill.getId());
                        record.setRemainingId(saveRemaining.getId());
                        record.setOperateMoney(operateMoney);
                        record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                        record.setLastUpdateTime(updateTime);
                        record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                        record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                        record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                        record.setBillStatus(PaymentTypeEnum.EXPENSE_BILL.getValue());
                        // 状态：1正常 2已删除
                        record.setStatus(1);
                        houseRemainingRecordRepository.save(record);

                        // 余额变动待办事项
                        houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), expenseBill.getChargeType(), operateMoney, null, saveBill.getOrgId());
                    } else {
                        operateMoney = cost;
                        // 账单费用扣减
                        cost = Integer.parseInt(remaining.subtract(billCost).toString());
                        expenseBill.setSurplusCost(0);
                        expenseBill.setPaymentTime(updateTime);
                        expenseBill.setPaymentChannel(PaymentTypeEnum.Remaining.getValue());
                        expenseBill.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                        EstateExpenseBill saveBill = estateExpenseBillRepository.save(expenseBill);

                        // 余额扣减
                        houseRemaining.setBalanceFee(cost);
                        houseRemaining.setLastUpdateTime(updateTime);
                        HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                        // 余额操作记录
                        HouseRemainingRecord record = new HouseRemainingRecord();
                        record.setBillId(saveBill.getId());
                        record.setRemainingId(saveRemaining.getId());
                        record.setOperateMoney(operateMoney);
                        record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                        record.setLastUpdateTime(updateTime);
                        record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                        record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                        record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                        record.setBillStatus(PaymentTypeEnum.EXPENSE_BILL.getValue());
                        // 状态：1正常 2已删除
                        record.setStatus(1);
                        houseRemainingRecordRepository.save(record);

                        // 余额变动待办事项
                        houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), expenseBill.getChargeType(), operateMoney, null, saveBill.getOrgId());
                        // 其他费用待办事项
                        propertyOtherItem(saveBill.getId());
                    }
                }
            } else {
                Long billId = Long.parseLong(bill.get("billId").toString());
                Optional<EstateRentBill> rentBillById = estateRentBillRepository.findById(billId);
                if (rentBillById.isPresent()) {
                    EstateRentBill estateRentBill = rentBillById.get();
                    Integer rentBillChargeType = estateRentBill.getChargeType();
                    Integer cost = estateRentBill.getSurplusCost();
                    BigDecimal billCost = new BigDecimal(cost);
                    BigDecimal remaining = new BigDecimal(balanceFee);
                    if (rentBillChargeType == 1) {// 租金
                        if (balanceFee - cost <= 0) {
                            operateMoney = balanceFee;

                            int paymentStatus = DeductionEnum.PART_PAY.getValue();
                            if (balanceFee - cost == 0) {
                                paymentStatus = DeductionEnum.ALL_PAY.getValue();
                            }
                            // 账单费用抵扣
                            cost = Integer.parseInt(billCost.subtract(remaining).toString());
                            estateRentBill.setSurplusCost(cost);
                            estateRentBill.setPaymentStatus(paymentStatus);
                            estateRentBill.setPaymentTime(updateTime);
                            EstateRentBill saveBill = estateRentBillRepository.save(estateRentBill);

                            // 余额扣减
                            houseRemaining.setBalanceFee(0);
                            houseRemaining.setLastUpdateTime(updateTime);
                            HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                            // 余额操作记录
                            HouseRemainingRecord record = new HouseRemainingRecord();
                            record.setBillId(saveBill.getId());
                            record.setRemainingId(saveRemaining.getId());
                            record.setOperateMoney(operateMoney);
                            record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                            record.setLastUpdateTime(updateTime);
                            record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                            record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                            record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                            record.setBillStatus(PaymentTypeEnum.RENT_BILL.getValue());
                            // 状态：1正常 2已删除
                            record.setStatus(1);
                            houseRemainingRecordRepository.save(record);

                            // 余额变动待办事项
                            houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), estateRentBill.getChargeType() == 1 ? 8 : 9, operateMoney, null, saveBill.getOrgId());
                        } else {
                            operateMoney = cost;
                            // 账单费用扣减
                            cost = Integer.parseInt(remaining.subtract(billCost).toString());
                            estateRentBill.setSurplusCost(0);
                            estateRentBill.setPaymentTime(updateTime);
                            estateRentBill.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                            EstateRentBill saveBill = estateRentBillRepository.save(estateRentBill);

                            // 余额扣减
                            houseRemaining.setBalanceFee(cost);
                            houseRemaining.setLastUpdateTime(updateTime);
                            HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                            // 余额操作记录
                            HouseRemainingRecord record = new HouseRemainingRecord();
                            record.setBillId(saveBill.getId());
                            record.setRemainingId(saveRemaining.getId());
                            record.setOperateMoney(operateMoney);
                            record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                            record.setLastUpdateTime(updateTime);
                            record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                            record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                            record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                            record.setBillStatus(PaymentTypeEnum.RENT_BILL.getValue());
                            // 状态：1正常 2已删除
                            record.setStatus(1);
                            houseRemainingRecordRepository.save(record);

                            // 余额变动待办事项
                            houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), estateRentBill.getChargeType() == 1 ? 8 : 9, operateMoney, null, saveBill.getOrgId());
                            // 租金/押金待办事项
                            propertyRentItem(saveBill.getId());
                        }
                    } else {
                        // 押金
                        if (balanceFee - cost <= 0) {
                            operateMoney = balanceFee;

                            int paymentStatus = DeductionEnum.PART_PAY.getValue();
                            if (balanceFee - cost == 0) {
                                paymentStatus = DeductionEnum.ALL_PAY.getValue();
                            }
                            // 账单费用抵扣
                            cost = Integer.parseInt(billCost.subtract(remaining).toString());
                            estateRentBill.setSurplusCost(cost);
                            estateRentBill.setPaymentStatus(paymentStatus);
                            estateRentBill.setPaymentTime(updateTime);
                            EstateRentBill saveBill = estateRentBillRepository.save(estateRentBill);

                            // 余额扣减
                            houseRemaining.setBalanceFee(0);
                            houseRemaining.setCashPledge(operateMoney);
                            houseRemaining.setLastUpdateTime(updateTime);
                            HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                            // 余额操作记录
                            HouseRemainingRecord record = new HouseRemainingRecord();
                            record.setBillId(saveBill.getId());
                            record.setRemainingId(saveRemaining.getId());
                            record.setOperateMoney(operateMoney);
                            record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                            record.setLastUpdateTime(updateTime);
                            record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                            record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                            record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                            record.setBillStatus(PaymentTypeEnum.DEPOSIT_BILL.getValue());
                            // 状态：1正常 2已删除
                            record.setStatus(1);
                            houseRemainingRecordRepository.save(record);

                            // 余额变动待办事项
                            houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), estateRentBill.getChargeType() == 1 ? 8 : 9, operateMoney, null, saveBill.getOrgId());
                        } else {
                            operateMoney = cost;
                            // 账单费用扣减
                            cost = Integer.parseInt(remaining.subtract(billCost).toString());
                            estateRentBill.setSurplusCost(0);
                            estateRentBill.setPaymentTime(updateTime);
                            estateRentBill.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                            EstateRentBill saveBill = estateRentBillRepository.save(estateRentBill);

                            // 余额扣减
                            houseRemaining.setBalanceFee(cost);
                            houseRemaining.setCashPledge(operateMoney);
                            houseRemaining.setLastUpdateTime(updateTime);
                            HouseRemaining saveRemaining = houseRemainingRepository.save(houseRemaining);

                            // 余额操作记录
                            HouseRemainingRecord record = new HouseRemainingRecord();
                            record.setBillId(saveBill.getId());
                            record.setRemainingId(saveRemaining.getId());
                            record.setOperateMoney(operateMoney);
                            record.setOperateName(SystemEnum.SYSTEM_USER_NAME.getValue());
                            record.setLastUpdateTime(updateTime);
                            record.setUpdateStatus(PaymentTypeEnum.SUCCESS.getValue());
                            record.setCause(PaymentCauseEnum.SYSTEM_DEDUCTION.getValue());
                            record.setOperateStatus(PaymentTypeEnum.BUCKLE.getValue());
                            record.setBillStatus(PaymentTypeEnum.DEPOSIT_BILL.getValue());
                            // 状态：1正常 2已删除
                            record.setStatus(1);
                            houseRemainingRecordRepository.save(record);

                            // 余额变动待办事项
                            houseRemainingItem(saveBill.getHouseId(), saveBill.getMatchUserId(), saveRemaining.getId(), estateRentBill.getChargeType() == 1 ? 8 : 9, operateMoney, null, saveBill.getOrgId());
                            // 租金/押金待办事项
                            propertyRentItem(saveBill.getId());
                        }
                    }
                }
            }

        }


    }

    /**
     * 非公租房其他账单待办事项
     */
    public void propertyOtherItem(Long billId) {
        List<BacklogItemPropertyOtherBill> propertyOtherBill = backlogItemPropertyOtherBillRepository.findByBillId(billId);
        if (propertyOtherBill != null && propertyOtherBill.size() > 0) {
            Date date = new Date();
            for (BacklogItemPropertyOtherBill bill : propertyOtherBill) {
                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                if (itemOpt.isPresent()) {
                    BacklogItem item = itemOpt.get();
                    item.setBusinessStatus("已缴费");
                    item.setHandleStatus(1);
                    item.setHandlerTime(date);
                    backlogItemRepository.save(item);
                }
            }
        }

    }

    /**
     * 非公租房租金待办事项
     */
    public void propertyRentItem(Long billId) {
        List<BacklogItemPropertyRentBill> propertyRentBill = backlogItemPropertyRentBillRepository.findByRentBillIdOrDepositBillId(billId, billId);
        if (propertyRentBill != null && propertyRentBill.size() > 0) {
            Date date = new Date();
            for (BacklogItemPropertyRentBill bill : propertyRentBill) {
                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                if (itemOpt.isPresent()) {
                    BacklogItem item = itemOpt.get();
                    item.setBusinessStatus("已缴费");
                    item.setHandleStatus(1);
                    item.setHandlerTime(date);
                    backlogItemRepository.save(item);
                }
            }
        }
    }

    /**
     * 余额扣款待办事项
     *
     * @param houseId     房屋ID
     * @param matchUserId 承租人ID
     * @param remainingId 余额ID
     * @param chargeType  扣款类型 1水费 2电费 3物业费 4宽带费 5电视费 6煤气费 7暖气费 8租金 9押金
     * @param cost        金额
     * @param operatorId  操作人ID
     * @param orgId       收款机构ID
     */
    public void houseRemainingItem(String houseId, String matchUserId, Long remainingId, Integer chargeType, Integer cost, String operatorId, Long orgId) {
        String yuan = fenToYuan(String.valueOf(cost));
        String chargeName = null;
        switch (chargeType) {  //  1水费 2电费 3物业费 4宽带费 5电视费 6煤气费 7暖气费 8租金 9押金
            case 1:
                chargeName = "水费";
                break;
            case 2:
                chargeName = "电费";
                break;
            case 3:
                chargeName = "物业费";
                break;
            case 4:
                chargeName = "宽带费";
                break;
            case 5:
                chargeName = "电视费";
                break;
            case 6:
                chargeName = "燃气费";
                break;
            case 7:
                chargeName = "暖气费";
                break;
            case 8:
                chargeName = "租金";
                break;
            case 9:
                chargeName = "押金";
                break;
        }

//        String sql="select * from (\n" +
//                "select a.mobile as mobile ,a.community_house_id as houseId  , a.user_id as userId  from  saas_community_house_user a\n" +
//                "where   a.status = 1 \n" +
//                "UNION\n" +
//                "select b.phone as mobile , a.house_id as houseId , a.match_user_id as userId from   saas_house_match_user a \n" +
//                "LEFT JOIN saas_app_user b on b.id= a.match_user_id\n" +
//                "where 1=1\n" +
//                "UNION \n" +
//                "select b.mobile as mobile , a.house_id as houseId , c.id as userId from   saas_house_match_user a \n" +
//                "LEFT JOIN saas_house_eligible_apply_cohabit b on b.apply_id= a.apply_id\n" +
//                "LEFT JOIN saas_app_user c on c.phone = b.mobile \n" +
//                "where 1=1 and b.mobile is not null \n" +
//                ") t1 where t1.houseId ='"+houseId+"' ";

        /**
         * qixi
         * 2022-12-28 11:32
         * 余额变动承租人和已授权账单的同住人可见
         *
         */
        String sql = "select * from (select a.mobile as mobile ,a.community_house_id as houseId  , a.user_id as userId  " +
                "from  saas_community_house_user a\n" +
                "where a.status = 1 and a.type = 1  \n" +
                "UNION\n" +
                "select b.phone as mobile , a.house_id as houseId , a.match_user_id as userId from   saas_house_match_user a\n" +
                "LEFT JOIN saas_app_user b on b.id= a.match_user_id\n" +
                "where 1=1\n" +
                ") t1 where t1.houseId ='" + houseId + "' ";


        String where = " and 1=1 ";

        List<CommunityHouseUser> CommunityHouseUserList = jdbcTemplate.query(sql + where, new BeanPropertyRowMapper<>(CommunityHouseUser.class));

        CommunityHouseUserList = CommunityHouseUserList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(CommunityHouseUser::getMobile))), ArrayList::new));
        for (CommunityHouseUser communityHouseUser : CommunityHouseUserList) {
            // 账单扣款余额变动
            BacklogItem backlogItem = new BacklogItem();
            backlogItem.setHouseId(houseId);
            backlogItem.setOrgId(orgId);
            backlogItem.setType(BacklogItemTypeEnum.REMAINING_CHANGE.getValue());
            backlogItem.setTitle("余额变动");
            backlogItem.setContent(chargeName + "账单，系统扣款：" + yuan + "元");
            backlogItem.setBusinessStatus("待查看");
            backlogItem.setHandleStatus(0);
            backlogItem.setMatchUserId(matchUserId);
            backlogItem.setPhone(communityHouseUser.getMobile());
            backlogItem.setCreateTime(new Date());
            BacklogItem save = backlogItemRepository.save(backlogItem);

            BacklogItemHouseRemaining houseRemaining = new BacklogItemHouseRemaining();
            houseRemaining.setBacklogItemId(save.getId());
            houseRemaining.setRemainingId(remainingId);
            backlogItemHouseRemainingRepository.save(houseRemaining);




            Optional<AppUser> byId = appUserRepository.findById(matchUserId);
            if (byId.isPresent()){
                Optional<HouseRemaining> byRemainingId = houseRemainingRepository.findById(remainingId);
                HouseRemaining houseRemaining1 = byRemainingId.get();
                AppUser appUser = byId.get();

                SubscribeVo subscribeVo = new SubscribeVo();
                subscribeVo.setCost(Double.valueOf(yuan));
                subscribeVo.setOpenId(appUser.getOpenId());
                subscribeVo.setBillTypeName("支付"+chargeName);
                subscribeVo.setBalanceFee(fenToYuan(houseRemaining1.getBalanceFee().toString()));

                subscribeService.sendDeductionBalanceMsg(subscribeVo);
            }

        }
    }

    /**
     * 费用管理-租金/押金账单明细
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     */
    public void handleBill(String outTradeNo, Map<String, String> result, Integer totalAmount) throws Exception {
        LOG.info("WxPayService handleBill<微信app公租房租金/押金账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("WxPayService appPayCallback<微信app公租房租金/押金支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        List<RentBill> bills = rentBillRepository.findByIdIn(redisVo.getIds());
        if (CollectionUtils.isEmpty(bills)) {
            LOG.error("WxPayService appPayCallback<微信app公租房租金/押金支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }

        Date payTime = new Date();
        Integer billAmount = 0;

        List<HousePaymentOrderRelation> porList = new ArrayList<>();
        for (RentBill b : bills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList.add(por);
        }

        // 更新账单明细支付状态
        rentBillRepository.saveAll(bills);
        housePaymentOrderRelationRepository.saveAll(porList);

        /**
         * 验证租金、押金是否都支付完成，全部支付完成，才能修改公租房与合同状态
         */
        // 根据当前支付的账单明细，找到缴费账单对应的所有合同
        List<RentBillRelation> relationList = rentBillRelationRepository.findByRentBillIdIn(redisVo.getIds());
        Map<String, String> houseMap = new HashMap<>();
        List<String> contractNubmers = new ArrayList<>();
        for (RentBillRelation r : relationList) {
            houseMap.put(r.getContractNubmer(), r.getHouseId());
            contractNubmers.add(r.getContractNubmer());
        }
        contractNubmers = contractNubmers.stream().distinct().collect(Collectors.toList());
        // 查询拥有未支付的合同信息
        List<RentBillRelation> noPayBillList = rentBillRelationRepository.findNoPayBill(contractNubmers);

        // 保存全部支付完成(租金 + 押金)的合同编号
        List<String> completedContracts = new ArrayList<>();
        // 保存全部支付完成的公租房id
        List<String> houseIds = new ArrayList<>();

        // 验证合同是否支付完成
        Map<String, String> map = noPayBillList.stream().collect(Collectors.toMap(RentBillRelation::getContractNubmer, RentBillRelation::getHouseId));
        for (String contractNumber : contractNubmers) {
            String houseId = map.get(contractNumber);
            if (houseId == null) {
                completedContracts.add(contractNumber);
                String sHouseId = houseMap.get(contractNumber);
                if (StringUtils.isNotBlank(sHouseId)) {
                    houseIds.add(sHouseId);
                }
            }
        }

        // 更新公租房合同缴费状态
        if (!houseIds.isEmpty()) {
            List<House> houseList = houseRepository.findByIdIn(houseIds);
            houseList.forEach(h -> h.setPaymentStatus(HousePaymentStatusEnum.COMPLETE_PAY.getValue()));
            houseRepository.saveAll(houseList);
        }

        // 更新"已确认待交租"的合同状态
        if (!completedContracts.isEmpty()) {
            List<Contract> contractList = contractRepository.findByStatusAndContractNubmerIn(ContractStatusEnum.WAITING_RENT.getValue(), completedContracts);
            contractList.forEach(c -> c.setStatus(ContractStatusEnum.WAITING_RECORD.getValue()));
            contractRepository.saveAll(contractList);

            Date date = new Date();
            for (String contractNumber : completedContracts) {
                // 更新租金/押金待办事项状态
                List<BacklogItemContractBill> contractBill = backlogItemContractBillRepository.findByContractNumber(contractNumber);
                if (contractBill != null && contractBill.size() > 0) {
                    for (BacklogItemContractBill bill : contractBill) {
                        Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                        if (itemOpt.isPresent()) {
                            BacklogItem item = itemOpt.get();
                            item.setBusinessStatus("已缴费");
                            item.setHandleStatus(1);
                            item.setHandlerTime(date);
                            backlogItemRepository.save(item);
                        }
                    }

                }
                // 生成信息备案待提交待办事项
                Contract contract = contractRepository.findByContractNubmer(contractNumber);
                if (contract == null) {
                    LOG.error("WxPayService appPayCallback<微信app公租房租金/押金支付回调> 未找到合同信息, contractNumber={}", contractNumber);
                    return;
                }

                AppUser appUsers = null;
                if (StringUtils.isNotBlank(contract.getMatchUserId())) {
                    appUsers = appUserRepository.findByIdOrEnterpriseUserId(contract.getMatchUserId(), contract.getMatchUserId());
                }

                BacklogItem submitItem = new BacklogItem();
                submitItem.setHouseId(contract.getHouseId());
                submitItem.setType(BacklogItemTypeEnum.RECORD_SUBMIT.getValue());
                submitItem.setTitle("公租房信息备案待提交");
                submitItem.setBusinessStatus("待提交");
                submitItem.setHandleStatus(0);
                submitItem.setMatchUserId(contract.getMatchUserId());
                submitItem.setPhone(appUsers != null ? appUsers.getPhone() : null);
                submitItem.setCreateTime(new Date());
                BacklogItem save = backlogItemRepository.save(submitItem);

                BacklogItemRecordSubmit submit = new BacklogItemRecordSubmit();
                submit.setBacklogItemId(save.getId());
                submit.setMatchUserId(contract.getMatchUserId());
                backlogItemRecordSubmitRepository.save(submit);
            }
        }

        // 公租房租金待办事项
        rentBillBacklogItem(redisVo.getIds());

        HousePaymentOrder paymentOrder = new HousePaymentOrder();
        paymentOrder.setBillAmount(billAmount);
        paymentOrder.setOrderNumber(outTradeNo);
        paymentOrder.setPayType(1);
        paymentOrder.setPayMode(redisVo.getPaymentMode());
        paymentOrder.setPayTime(payTime);
        paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
        // 手续费 千分之6
        Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        paymentOrder.setWxCommissionAmount(payHandlingFee);
        paymentOrder.setPayUserId(redisVo.getUserId());
        paymentOrder.setTotalAmount(totalAmount);
        paymentOrder.setPayResult(1);
        housePaymentOrderRepository.save(paymentOrder);

        SaasHouseWxPay wxpay = new SaasHouseWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        saasHouseWxPayRepository.save(wxpay);

        // DepartmentHierarchy department
        // =departmentHierarchyRepository.findByOrgId(redisVo.getOrgId());

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        aliPayService.updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo,
                payTime, PaymentTypeEnum.WECHAT.getValue());
    }

    /**
     * 维修
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     */
    public void handleRepairs(String outTradeNo, Map<String, String> result, Integer totalAmount) throws Exception {

        LOG.info("WxPayService handleRepairs<微信app维修支付回调> outTradeNo={}", outTradeNo);
        RepairsPaymentRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, RepairsPaymentRedisVo.class);
        redisVo.setPaymentStatus(1);
        redisService.putPaymentRepairs(redisVo);
        Date payTime = new Date();

        Optional<EstateRepairsRecord> recordOpt = estateRepairsRecordRepository.findById(redisVo.getRepairsId());
        EstateRepairsRecord record = recordOpt.get();
        record.setStatus(RepairsStatusEnum.COMPLETED.getStatus());
        record.setPaymentTime(payTime);
        estateRepairsRecordRepository.save(record);

        // 更新支付记录
        RepairsPaymentOrder payment = new RepairsPaymentOrder();
        payment.setRepairsId(record.getId());
        payment.setOrderNumber(outTradeNo);
        payment.setPayResult(1);
        payment.setPayUserId(redisVo.getUserId());
        payment.setTotalAmount(totalAmount);
        payment.setPayTime(payTime);
        payment.setPayType(1);
        repairsPaymentOrderRepository.save(payment);

        // 更新微信记录
        SaasRepairsWxPay wxpay = new SaasRepairsWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        saasRepairsWxPayRepository.save(wxpay);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        aliPayService.updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, totalAmount, outTradeNo,
                payTime, PaymentTypeEnum.WECHAT.getValue());
    }

    /**
     * 待办事项
     *
     * @param
     * @param
     * @throws Exception
     */
    public void handleBacklog(String outTradeNo, Map<String, String> result, Integer totalAmount) throws Exception {

        LOG.info("WxPayService handleBacklog<微信待办事项支付回调> outTradeNo={}", outTradeNo);
        BacklogItemRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, BacklogItemRedisVo.class);
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBacklog(redisVo);

        Optional<BacklogItem> itemOptional = backlogItemRepository.findById(redisVo.getId());
        Date payTime = new Date();
        BacklogItem logItem = itemOptional.get();
        logItem.setHandleStatus(1);
        logItem.setHandlerTime(payTime);
        backlogItemRepository.save(logItem);

        List<RentBill> bills = rentBillRepository.findByIdIn(redisVo.getIds());

        if (CollectionUtils.isEmpty(bills)) {
            LOG.error("WxPayService handleBacklog<微信待办事项支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }

        Integer billAmount = 0;

        List<HousePaymentOrderRelation> porList = new ArrayList<>();
        Integer chargeType = null;
        for (RentBill b : bills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            if (chargeType == null && b.getChargeType() == ChargeTypeEnum.RENT.getValue()) {
                chargeType = ChargeTypeEnum.RENT.getValue();
            }
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            billAmount += b.getCost();
            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList.add(por);
        }

        rentBillRepository.saveAll(bills);
        housePaymentOrderRelationRepository.saveAll(porList);

        /*
         * // 租金交钱，更新合同状态及房租状态 if (chargeType != null && chargeType ==
         * ChargeTypeEnum.RENT.getValue()) { // 账单合同房租关系 List<RentBillRelation>
         * relationList =
         * rentBillRelationRepository.findByRentBillIdIn(redisVo.getIds());
         * List<String> houseIds = new ArrayList<>(); List<String>
         * contractNubmers = new ArrayList<>(); relationList.forEach(r -> {
         * houseIds.add(r.getHouseId());
         * contractNubmers.add(r.getContractNubmer()); });
         *
         * List<House> houseList = houseRepository.findByIdIn(houseIds);
         *
         * houseList.forEach(h -> h.setPaymentStatus(1));
         * houseRepository.saveAll(houseList);
         *
         * List<Contract> contractList =
         * contractRepository.findByContractNubmerIn(contractNubmers);
         *
         * contractList.forEach(c -> c.setStatus(7));
         *
         * contractRepository.saveAll(contractList); }
         */

        HousePaymentOrder paymentOrder = new HousePaymentOrder();
        paymentOrder.setBillAmount(billAmount);
        paymentOrder.setOrderNumber(outTradeNo);
        paymentOrder.setPayType(1);
        paymentOrder.setPayMode(redisVo.getPaymentMode());
        paymentOrder.setPayTime(payTime);
        paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
        // 手续费 千分之6
        Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        paymentOrder.setWxCommissionAmount(payHandlingFee);
        paymentOrder.setPayUserId(redisVo.getUserId());
        paymentOrder.setTotalAmount(totalAmount);
        paymentOrder.setPayResult(1);
        housePaymentOrderRepository.save(paymentOrder);

        SaasHouseWxPay wxpay = new SaasHouseWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        saasHouseWxPayRepository.save(wxpay);

        if (logItem.getType() == BacklogItemTypeEnum.RENT_BILL.getValue()) {
            // 押金/租金支付成功后，解冻智能锁
            List<SmartLock> lockList = smartLockRepository.findByHouseId(logItem.getHouseId());
            List<Long> lockIds = lockList.stream().map(SmartLock::getId).collect(Collectors.toList());

            // 查询账单id，解冻
            List<BacklogItemLock> blocks = backlogItemLockRepository.findByBacklogItemId(logItem.getId());
            List<Long> billIds = blocks.stream().map(BacklogItemLock::getBillId).collect(Collectors.toList());

            Map<String, List<Long>> map = new HashMap<>();
            map.put("lockIds", lockIds);
            map.put("billIds", billIds);
            smartLockCallBackService.backlogItemLock(map, "job-executor-thaw");
        }

        // DepartmentHierarchy department
        // =departmentHierarchyRepository.findByOrgId(redisVo.getOrgId());

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        aliPayService.updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo,
                payTime, PaymentTypeEnum.WECHAT.getValue());
    }

    /**
     * 物业房产-租金/押金
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     */
    public void houseHandleBill(String outTradeNo, Map<String, String> result, Integer totalAmount) throws Exception {
        LOG.info("WxPayService houseHandleBill<微信app物业房产租金/押金账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("WxPayService houseHandleBill<微信app物业房产租金/押金支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        List<EstateRentBill> bills = estateRentBillRepository.findByIdIn(redisVo.getIds());
        if (CollectionUtils.isEmpty(bills)) {
            LOG.error("WxPayService houseHandleBill<微信app物业房产租金/押金支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }

        Date payTime = new Date();
        Integer billAmount = 0;

        List<EstatePaymentOrderRelation> porList = new ArrayList<>();
        for (EstateRentBill b : bills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList.add(por);
        }

        // 更新租金/押金账单明细支付状态
        estateRentBillRepository.saveAll(bills);
        // 新增账单与支付关系明细
        estatePaymentOrderRelationRepository.saveAll(porList);

        // 修改待办事项的状态
        propertyRentItem(redisVo.getIds());

        // 新增账单支付记录
        EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
        paymentOrder.setBillAmount(billAmount);
        paymentOrder.setOrderNumber(outTradeNo);
        paymentOrder.setPayType(1);
        paymentOrder.setPayMode(redisVo.getPaymentMode());
        paymentOrder.setPayTime(payTime);
        paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
        // 手续费 千分之6
        Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        paymentOrder.setWxCommissionAmount(payHandlingFee);
        paymentOrder.setPayUserId(redisVo.getUserId());
        paymentOrder.setTotalAmount(totalAmount);
        paymentOrder.setPayResult(1);
        estatePaymentOrderRepository.save(paymentOrder);

        // 新增微信支付明细
        EstateWxPay wxpay = new EstateWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        estateWxPayRepository.save(wxpay);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        aliPayService.updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo,
                payTime, PaymentTypeEnum.WECHAT.getValue());
    }

    /**
     * 费用管理-公租房其它费用账单
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     * @author shun
     * @date 2021年7月12日
     */
    public void otherHandleBill(String outTradeNo, Map<String, String> result, Integer totalAmount) throws Exception {
        LOG.info("WxPayService otherHandleBill<微信app公租房其它费用账单账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("WxPayService otherHandleBill<微信app公租房其它费用账单支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        List<ExpenseBill> expenseBills = expenseBillRepository.findByIdIn(redisVo.getIds());
        if (CollectionUtils.isEmpty(expenseBills)) {
            LOG.error("WxPayService otherHandleBill<微信app公租房其它费用账单支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }
        LOG.info("WxPayService otherHandleBill, redisVo={}, expenseBills={}", JSON.toJSONString(redisVo),
                JSON.toJSONString(expenseBills));

        Date payTime = new Date();
        Integer billAmount = 0;

        List<HousePaymentOrderRelation> porList = new ArrayList<>();
        for (ExpenseBill b : expenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                // 退租
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                // 更新退租账单状态
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList.add(por);
        }

        // 更新账单明细支付状态
        expenseBillRepository.saveAll(expenseBills);
        housePaymentOrderRelationRepository.saveAll(porList);

        // 公租房其他费用待办事项
        houseOtherBillItem(redisVo.getIds());

        HousePaymentOrder paymentOrder = new HousePaymentOrder();
        paymentOrder.setBillAmount(billAmount);
        paymentOrder.setOrderNumber(outTradeNo);
        paymentOrder.setPayType(1);
        paymentOrder.setPayMode(redisVo.getPaymentMode());
        paymentOrder.setPayTime(payTime);
        paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
        // 手续费 千分之6
        Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        paymentOrder.setWxCommissionAmount(payHandlingFee);
        paymentOrder.setPayUserId(redisVo.getUserId());
        paymentOrder.setTotalAmount(totalAmount);
        paymentOrder.setPayResult(1);
        housePaymentOrderRepository.save(paymentOrder);

        SaasHouseWxPay wxpay = new SaasHouseWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        saasHouseWxPayRepository.save(wxpay);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        aliPayService.updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo,
                payTime, PaymentTypeEnum.WECHAT.getValue());
    }

    /**
     * 费用管理-物业房产其它费用账单
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     * @throws Exception
     * @author shun
     * @date 2021年7月12日
     */
    public void otherEstateHandleBill(String outTradeNo, Map<String, String> result, Integer totalAmount)
            throws Exception {
        LOG.info("WxPayService otherEstateHandleBill<微信app物业房产其它费用账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("WxPayService otherEstateHandleBill<微信app物业房产其它费用支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        List<EstateExpenseBill> expenseBills = estateExpenseBillRepository.findByIdIn(redisVo.getIds());
        if (CollectionUtils.isEmpty(expenseBills)) {
            LOG.error("WxPayService otherEstateHandleBill<微信app物业房产其它费用支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }
        LOG.info("WxPayService otherEstateHandleBill, redisVo={}, expenseBills={}", JSON.toJSONString(redisVo),
                JSON.toJSONString(expenseBills));

        Date payTime = new Date();
        Integer billAmount = 0;

        List<EstatePaymentOrderRelation> porList = new ArrayList<>();
        for (EstateExpenseBill b : expenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                // 退租
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                // 更新退租账单状态
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList.add(por);
        }

        // 更新账单明细支付状态
        estateExpenseBillRepository.saveAll(expenseBills);
        estatePaymentOrderRelationRepository.saveAll(porList);

        // 物业其他费用待办事项
        propertyOtherItem(redisVo.getIds());

        // 新增账单支付记录
        EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
        paymentOrder.setBillAmount(billAmount);
        paymentOrder.setOrderNumber(outTradeNo);
        paymentOrder.setPayType(2);
        paymentOrder.setPayMode(redisVo.getPaymentMode());
        paymentOrder.setPayTime(payTime);
        paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
        // 手续费 千分之6
        Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        paymentOrder.setWxCommissionAmount(payHandlingFee);
        paymentOrder.setPayUserId(redisVo.getUserId());
        paymentOrder.setTotalAmount(totalAmount);
        paymentOrder.setPayResult(1);
        estatePaymentOrderRepository.save(paymentOrder);

        // 新增微信支付明细
        EstateWxPay wxpay = new EstateWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        estateWxPayRepository.save(wxpay);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        aliPayService.updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo,
                payTime, PaymentTypeEnum.WECHAT.getValue());
    }

    /**
     * 生活缴费
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     */
    /*public void handleLifePay(String outTradeNo, Map<String, String> result, Integer totalAmount) {
        LOG.info("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        Date payTime = new Date();
        Integer billAmount = 0;

        if (redisVo.getType() == 1) {
            List<RentBill> rentBills = new ArrayList<>();
            List<ExpenseBill> expenseBills = new ArrayList<>();
            if (!CollectionUtils.isEmpty(redisVo.getIds())) {
                rentBills = rentBillRepository.findByIdIn(redisVo.getIds());
            }
            if (!CollectionUtils.isEmpty(redisVo.getExpenseIds())) {
                expenseBills = expenseBillRepository.findByIdIn(redisVo.getExpenseIds());
            }

            if (CollectionUtils.isEmpty(rentBills) && CollectionUtils.isEmpty(expenseBills)) {
                LOG.error("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
                return;
            }

            LOG.info("WxPayService handleLifePay, redisVo={}, rentBills={}, expenseBills={}", JSON.toJSONString(redisVo), JSON.toJSONString(rentBills),
                    JSON.toJSONString(expenseBills));

            List<HousePaymentOrderRelation> porList = new ArrayList<>();
            for (RentBill b : rentBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(1);
                billAmount += b.getCost();

                HousePaymentOrderRelation por = new HousePaymentOrderRelation();
                por.setOrderNumber(outTradeNo);
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
                }
                porList.add(por);
            }
            rentBillRepository.saveAll(rentBills);

            for (ExpenseBill b : expenseBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(1);
                billAmount += b.getCost();

                HousePaymentOrderRelation por = new HousePaymentOrderRelation();
                por.setOrderNumber(outTradeNo);
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                // 其它费用类型转换
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
                } else if (b.getChargeType() == 3) {
                    por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
                } else if (b.getChargeType() == 4) {
                    por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
                } else if (b.getChargeType() == 5) {
                    por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
                } else if (b.getChargeType() == 6) {
                    por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
                } else if (b.getChargeType() == 7) {
                    por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
                }
                porList.add(por);
            }
            expenseBillRepository.saveAll(expenseBills);

            housePaymentOrderRelationRepository.saveAll(porList);

            //验证租金、押金是否都支付完成，全部支付完成，才能修改公租房与合同状态
            if (!CollectionUtils.isEmpty(redisVo.getIds())) {
                // 根据当前支付的账单明细，找到缴费账单对应的所有合同
                List<RentBillRelation> relationList = rentBillRelationRepository.findByRentBillIdIn(redisVo.getIds());
                Map<String, String> houseMap = new HashMap<>();
                List<String> contractNubmers = new ArrayList<>();
                for (RentBillRelation r : relationList) {
                    houseMap.put(r.getContractNubmer(), r.getHouseId());
                    contractNubmers.add(r.getContractNubmer());
                }
                contractNubmers = contractNubmers.stream().distinct().collect(Collectors.toList());
                // 查询拥有未支付的合同信息
                List<RentBillRelation> noPayBillList = rentBillRelationRepository.findNoPayBill(contractNubmers);

                // 保存全部支付完成(租金 + 押金)的合同编号
                List<String> completedContracts = new ArrayList<>();
                // 保存全部支付完成的公租房id
                List<String> houseIds = new ArrayList<>();

                // 验证合同是否支付完成
                Map<String, String> map = noPayBillList.stream()
                        .collect(Collectors.toMap(RentBillRelation::getContractNubmer, RentBillRelation::getHouseId));
                for (String contractNumber : contractNubmers) {
                    String houseId = map.get(contractNumber);
                    if (houseId == null) {
                        completedContracts.add(contractNumber);
                        String sHouseId = houseMap.get(contractNumber);
                        if (StringUtils.isNotBlank(sHouseId)) {
                            houseIds.add(sHouseId);
                        }
                    }
                }

                // 更新公租房合同缴费状态
                if (!houseIds.isEmpty()) {
                    List<House> houseList = houseRepository.findByIdIn(houseIds);
                    houseList.forEach(h -> h.setPaymentStatus(HousePaymentStatusEnum.COMPLETE_PAY.getValue()));
                    houseRepository.saveAll(houseList);
                }

                // 更新"已确认待交租"的合同状态
                if (!completedContracts.isEmpty()) {
                    List<Contract> contractList = contractRepository
                            .findByStatusAndContractNubmerIn(ContractStatusEnum.WAITING_RENT.getValue(), completedContracts);
                    contractList.forEach(c -> c.setStatus(ContractStatusEnum.WAITING_RECORD.getValue()));
                    contractRepository.saveAll(contractList);

                    Date date = new Date();
                    for (String contractNumber : completedContracts) {
                        //更新租金/押金待办事项状态
                        BacklogItemContractBill contractBill = backlogItemContractBillRepository.findByContractNumber(contractNumber);
                        if (contractBill != null) {
                            Optional<BacklogItem> itemOpt = backlogItemRepository.findById(contractBill.getBacklogItemId());
                            if (itemOpt.isPresent()) {
                                BacklogItem item = itemOpt.get();
                                item.setBusinessStatus("已缴费");
                                item.setHandleStatus(1);
                                item.setHandlerTime(date);
                                backlogItemRepository.save(item);
                            }
                        }
                        //生成信息备案待提交待办事项
                        Contract contract = contractRepository.findByContractNubmer(contractNumber);
                        if (contract == null) {
                            LOG.error("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到合同信息, contractNumber={}", contractNumber);
                            return;
                        }
                        BacklogItem submitItem = new BacklogItem();
                        submitItem.setHouseId(contract.getHouseId());
                        submitItem.setType(BacklogItemTypeEnum.RECORD_SUBMIT.getValue());
                        submitItem.setTitle("公租房信息备案待提交");
                        submitItem.setBusinessStatus("待提交");
                        submitItem.setHandleStatus(0);
                        submitItem.setMatchUserId(contract.getMatchUserId());
                        submitItem.setCreateTime(new Date());
                        BacklogItem save = backlogItemRepository.save(submitItem);

                        BacklogItemRecordSubmit submit = new BacklogItemRecordSubmit();
                        submit.setBacklogItemId(save.getId());
                        submit.setMatchUserId(contract.getMatchUserId());
                        backlogItemRecordSubmitRepository.save(submit);
                    }
                }
            }

            HousePaymentOrder paymentOrder = new HousePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            housePaymentOrderRepository.save(paymentOrder);
        }

        if (redisVo.getType() == 2) {
            List<EstateRentBill> estateRentBills = new ArrayList<>();
            List<EstateExpenseBill> estateExpenseBills = new ArrayList<>();
            if (!CollectionUtils.isEmpty(redisVo.getIds())) {
                estateRentBills = estateRentBillRepository.findByIdIn(redisVo.getIds());
            }
            if (!CollectionUtils.isEmpty(redisVo.getExpenseIds())) {
                estateExpenseBills = estateExpenseBillRepository.findByIdIn(redisVo.getExpenseIds());
            }

            if (CollectionUtils.isEmpty(estateRentBills) && CollectionUtils.isEmpty(estateExpenseBills)) {
                LOG.error("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
                return;
            }

            LOG.info("WxPayService handleLifePay, redisVo={}, estateRentBills={}, estateExpenseBills={}", JSON.toJSONString(redisVo), JSON.toJSONString(estateRentBills),
                    JSON.toJSONString(estateExpenseBills));

            List<EstatePaymentOrderRelation> porList = new ArrayList<>();
            for (EstateRentBill b : estateRentBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(1);
                billAmount += b.getCost();

                EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
                por.setOrderNumber(outTradeNo);
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
                }
                porList.add(por);
            }
            estateRentBillRepository.saveAll(estateRentBills);

            for (EstateExpenseBill b : estateExpenseBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(1);
                billAmount += b.getCost();

                EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
                por.setOrderNumber(outTradeNo);
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                // 其它费用类型转换
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
                } else if (b.getChargeType() == 3) {
                    por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
                } else if (b.getChargeType() == 4) {
                    por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
                } else if (b.getChargeType() == 5) {
                    por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
                } else if (b.getChargeType() == 6) {
                    por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
                } else if (b.getChargeType() == 7) {
                    por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
                }
                porList.add(por);
            }
            estateExpenseBillRepository.saveAll(estateExpenseBills);

            estatePaymentOrderRelationRepository.saveAll(porList);

            EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            estatePaymentOrderRepository.save(paymentOrder);
        }

        SaasHouseWxPay wxpay = new SaasHouseWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        saasHouseWxPayRepository.save(wxpay);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        aliPayService.updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo,
                payTime, PaymentTypeEnum.WECHAT.getValue());
    }*/
    public void handleLifePay(String outTradeNo, Map<String, String> result, Integer totalAmount) {
        LOG.info("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        Date payTime = new Date();
        Integer billAmount = 0;

        List<RentBill> rentBills = new ArrayList<>();
        List<ExpenseBill> expenseBills = new ArrayList<>();
        List<EstateRentBill> estateRentBills = new ArrayList<>();
        List<EstateExpenseBill> estateExpenseBills = new ArrayList<>();
        if (!CollectionUtils.isEmpty(redisVo.getIds())) {
            rentBills = rentBillRepository.findByIdIn(redisVo.getIds());
            // 公租房租金押金账单
            rentBillBacklogItem(redisVo.getIds());
        }
        if (!CollectionUtils.isEmpty(redisVo.getExpenseIds())) {
            expenseBills = expenseBillRepository.findByIdIn(redisVo.getExpenseIds());
            // 公租房其他费用
            houseOtherBillItem(redisVo.getExpenseIds());
        }
        if (!CollectionUtils.isEmpty(redisVo.getEstateRentIds())) {
            estateRentBills = estateRentBillRepository.findByIdIn(redisVo.getEstateRentIds());
            // 物业房租金押金账单
            propertyRentItem(redisVo.getEstateRentIds());
        }
        if (!CollectionUtils.isEmpty(redisVo.getEstateExpenseIds())) {
            estateExpenseBills = estateExpenseBillRepository.findByIdIn(redisVo.getEstateExpenseIds());
            // 物业其他费用
            propertyOtherItem(redisVo.getEstateExpenseIds());
        }

        if (CollectionUtils.isEmpty(rentBills) && CollectionUtils.isEmpty(expenseBills)
                && CollectionUtils.isEmpty(estateRentBills) && CollectionUtils.isEmpty(estateExpenseBills)) {
            LOG.error("WxPayService handleAioScanPay<微信生活缴费账单支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }

        List<HousePaymentOrderRelation> porList = new ArrayList<>();
        List<EstatePaymentOrderRelation> porList2 = new ArrayList<>();
        for (RentBill b : rentBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList.add(por);
        }
        rentBillRepository.saveAll(rentBills);

        for (ExpenseBill b : expenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                // 调用接口
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList.add(por);
        }
        expenseBillRepository.saveAll(expenseBills);

        for (EstateRentBill b : estateRentBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList2.add(por);
        }
        estateRentBillRepository.saveAll(estateRentBills);

        for (EstateExpenseBill b : estateExpenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                // 调用接口
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList2.add(por);
        }
        estateExpenseBillRepository.saveAll(estateExpenseBills);

        housePaymentOrderRelationRepository.saveAll(porList);
        estatePaymentOrderRelationRepository.saveAll(porList2);

        // 验证租金、押金是否都支付完成，全部支付完成，才能修改公租房与合同状态
        if (!CollectionUtils.isEmpty(redisVo.getIds())) {
            // 根据当前支付的账单明细，找到缴费账单对应的所有合同
            List<RentBillRelation> relationList = rentBillRelationRepository.findByRentBillIdIn(redisVo.getIds());
            Map<String, String> houseMap = new HashMap<>();
            List<String> contractNubmers = new ArrayList<>();
            for (RentBillRelation r : relationList) {
                houseMap.put(r.getContractNubmer(), r.getHouseId());
                contractNubmers.add(r.getContractNubmer());
            }
            contractNubmers = contractNubmers.stream().distinct().collect(Collectors.toList());
            // 查询拥有未支付的合同信息
            List<RentBillRelation> noPayBillList = rentBillRelationRepository.findNoPayBill(contractNubmers);

            // 保存全部支付完成(租金 + 押金)的合同编号
            List<String> completedContracts = new ArrayList<>();
            // 保存全部支付完成的公租房id
            List<String> houseIds = new ArrayList<>();

            // 验证合同是否支付完成
            Map<String, String> map = noPayBillList.stream().collect(Collectors.toMap(RentBillRelation::getContractNubmer, RentBillRelation::getHouseId));
            for (String contractNumber : contractNubmers) {
                String houseId = map.get(contractNumber);
                if (houseId == null) {
                    completedContracts.add(contractNumber);
                    String sHouseId = houseMap.get(contractNumber);
                    if (StringUtils.isNotBlank(sHouseId)) {
                        houseIds.add(sHouseId);
                    }
                }
            }

            // 更新公租房合同缴费状态
            if (!houseIds.isEmpty()) {
                List<House> houseList = houseRepository.findByIdIn(houseIds);
                houseList.forEach(h -> h.setPaymentStatus(HousePaymentStatusEnum.COMPLETE_PAY.getValue()));
                houseRepository.saveAll(houseList);
            }

            // 更新"已确认待交租"的合同状态
            if (!completedContracts.isEmpty()) {
                List<Contract> contractList = contractRepository
                        .findByStatusAndContractNubmerIn(ContractStatusEnum.WAITING_RENT.getValue(), completedContracts);
                contractList.forEach(c -> c.setStatus(ContractStatusEnum.WAITING_RECORD.getValue()));
                contractRepository.saveAll(contractList);

                Date date = new Date();
                for (String contractNumber : completedContracts) {
                    // 更新租金/押金待办事项状态
                    List<BacklogItemContractBill> contractBill = backlogItemContractBillRepository.findByContractNumber(contractNumber);
                    if (contractBill != null && contractBill.size() > 0) {
                        for (BacklogItemContractBill bill : contractBill) {
                            Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                            if (itemOpt.isPresent()) {
                                BacklogItem item = itemOpt.get();
                                item.setBusinessStatus("已缴费");
                                item.setHandleStatus(1);
                                item.setHandlerTime(date);
                                backlogItemRepository.save(item);
                            }
                        }

                    }
                    // 生成信息备案待提交待办事项
                    Contract contract = contractRepository.findByContractNubmer(contractNumber);
                    if (contract == null) {
                        LOG.error("WxPayService handleAioScanPay<微信一体机扫码账单支付回调> 未找到合同信息, contractNumber={}", contractNumber);
                        return;
                    }
                    AppUser appUsers = null;
                    if (StringUtils.isNotBlank(contract.getMatchUserId())) {
                        appUsers = appUserRepository.findByIdOrEnterpriseUserId(contract.getMatchUserId(), contract.getMatchUserId());
                    }
                    BacklogItem submitItem = new BacklogItem();
                    submitItem.setHouseId(contract.getHouseId());
                    submitItem.setType(BacklogItemTypeEnum.RECORD_SUBMIT.getValue());
                    submitItem.setTitle("公租房信息备案待提交");
                    submitItem.setBusinessStatus("待提交");
                    submitItem.setHandleStatus(0);
                    submitItem.setMatchUserId(contract.getMatchUserId());
                    submitItem.setPhone(appUsers != null ? appUsers.getPhone() : null);
                    submitItem.setCreateTime(new Date());
                    BacklogItem save = backlogItemRepository.save(submitItem);

                    BacklogItemRecordSubmit submit = new BacklogItemRecordSubmit();
                    submit.setBacklogItemId(save.getId());
                    submit.setMatchUserId(contract.getMatchUserId());
                    backlogItemRecordSubmitRepository.save(submit);
                }
            }
        }

        if (!CollectionUtils.isEmpty(rentBills) || !CollectionUtils.isEmpty(expenseBills)) {
            HousePaymentOrder paymentOrder = new HousePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            housePaymentOrderRepository.save(paymentOrder);
        }

        if (!CollectionUtils.isEmpty(estateRentBills) || !CollectionUtils.isEmpty(estateExpenseBills)) {
            EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            estatePaymentOrderRepository.save(paymentOrder);
        }

        SaasHouseWxPay wxpay = new SaasHouseWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        saasHouseWxPayRepository.save(wxpay);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        aliPayService.updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo,
                payTime, PaymentTypeEnum.WECHAT.getValue());
    }

    /**
     * 一体机扫码支付
     *
     * @param outTradeNo
     * @param result
     * @param totalAmount
     */
    public void handleAioScanPay(String outTradeNo, Map<String, String> result, Integer totalAmount) {
        LOG.info("WxPayService handleAioScanPay<微信一体机扫码账单支付回调> outTradeNo={}", outTradeNo);

        PaymentBillRedisVo redisVo = redisService.getPaymentOrder(outTradeNo, PaymentBillRedisVo.class);
        if (redisVo == null) {
            LOG.error("WxPayService handleAioScanPay<微信一体机扫码账单支付回调> 未找到支付账单缓存信息 outTradeNo={}", outTradeNo);
            return;
        }
        redisVo.setPaymentStatus(1);
        redisService.putPaymentBill(redisVo);

        Date payTime = new Date();
        Integer billAmount = 0;

        List<RentBill> rentBills = new ArrayList<>();
        List<ExpenseBill> expenseBills = new ArrayList<>();
        List<EstateRentBill> estateRentBills = new ArrayList<>();
        List<EstateExpenseBill> estateExpenseBills = new ArrayList<>();
        if (!CollectionUtils.isEmpty(redisVo.getIds())) {
            rentBills = rentBillRepository.findByIdIn(redisVo.getIds());
            // 公租房租金押金账单
            rentBillBacklogItem(redisVo.getIds());
        }
        if (!CollectionUtils.isEmpty(redisVo.getExpenseIds())) {
            expenseBills = expenseBillRepository.findByIdIn(redisVo.getExpenseIds());
            // 公租房其他费用
            houseOtherBillItem(redisVo.getExpenseIds());
        }
        if (!CollectionUtils.isEmpty(redisVo.getEstateRentIds())) {
            estateRentBills = estateRentBillRepository.findByIdIn(redisVo.getEstateRentIds());
            // 物业房租金押金账单
            propertyRentItem(redisVo.getEstateRentIds());
        }
        if (!CollectionUtils.isEmpty(redisVo.getEstateExpenseIds())) {
            estateExpenseBills = estateExpenseBillRepository.findByIdIn(redisVo.getEstateExpenseIds());
            // 物业其他费用
            propertyOtherItem(redisVo.getEstateExpenseIds());
        }

        if (CollectionUtils.isEmpty(rentBills) && CollectionUtils.isEmpty(expenseBills)
                && CollectionUtils.isEmpty(estateRentBills) && CollectionUtils.isEmpty(estateExpenseBills)) {
            LOG.error("WxPayService handleAioScanPay<微信一体机扫码账单支付回调> 未找到相关费用信息 outTradeNo={}", outTradeNo);
            return;
        }

        LOG.info("WxPayService handleAioScanPay<微信一体机扫码账单支付回调>, redisVo={}", JSON.toJSONString(redisVo));

        List<HousePaymentOrderRelation> porList = new ArrayList<>();
        List<EstatePaymentOrderRelation> porList2 = new ArrayList<>();
        for (RentBill b : rentBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList.add(por);
        }
        rentBillRepository.saveAll(rentBills);

        for (ExpenseBill b : expenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            HousePaymentOrderRelation por = new HousePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                // 退租
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                // 更新退租账单状态
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList.add(por);
        }
        expenseBillRepository.saveAll(expenseBills);

        for (EstateRentBill b : estateRentBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
            }
            porList2.add(por);
        }
        estateRentBillRepository.saveAll(estateRentBills);

        for (EstateExpenseBill b : estateExpenseBills) {
            if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                continue;
            }
            // 修改状态为已缴费
            b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
            b.setPaymentTime(payTime);
            b.setPaymentChannel(1);
            billAmount += b.getCost();

            EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
            por.setOrderNumber(outTradeNo);
            por.setBillId(b.getId());
            por.setPlatformCommissionAmount(redisVo.getPlat());
            por.setMerchantId(redisVo.getMerchantId());
            por.setBillAmount(b.getCost());
            // 其它费用类型转换
            if (b.getChargeType() == 1) {
                por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
            } else if (b.getChargeType() == 2) {
                por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
            } else if (b.getChargeType() == 3) {
                por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
            } else if (b.getChargeType() == 4) {
                por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
            } else if (b.getChargeType() == 5) {
                por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
            } else if (b.getChargeType() == 6) {
                por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
            } else if (b.getChargeType() == 7) {
                por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
            } else if (b.getChargeType() == 10) {
                por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                // 调用接口
                withDrawService.changeStatus(b.getId(), b.getHouseId());
            }
            porList2.add(por);
        }
        estateExpenseBillRepository.saveAll(estateExpenseBills);

        housePaymentOrderRelationRepository.saveAll(porList);
        estatePaymentOrderRelationRepository.saveAll(porList2);

        // 验证租金、押金是否都支付完成，全部支付完成，才能修改公租房与合同状态
        if (!CollectionUtils.isEmpty(redisVo.getIds())) {
            // 根据当前支付的账单明细，找到缴费账单对应的所有合同
            List<RentBillRelation> relationList = rentBillRelationRepository.findByRentBillIdIn(redisVo.getIds());
            Map<String, String> houseMap = new HashMap<>();
            List<String> contractNubmers = new ArrayList<>();
            for (RentBillRelation r : relationList) {
                houseMap.put(r.getContractNubmer(), r.getHouseId());
                contractNubmers.add(r.getContractNubmer());
            }
            contractNubmers = contractNubmers.stream().distinct().collect(Collectors.toList());
            // 查询拥有未支付的合同信息
            List<RentBillRelation> noPayBillList = rentBillRelationRepository.findNoPayBill(contractNubmers);

            // 保存全部支付完成(租金 + 押金)的合同编号
            List<String> completedContracts = new ArrayList<>();
            // 保存全部支付完成的公租房id
            List<String> houseIds = new ArrayList<>();

            // 验证合同是否支付完成
            Map<String, String> map = noPayBillList.stream().collect(Collectors.toMap(RentBillRelation::getContractNubmer, RentBillRelation::getHouseId));
            for (String contractNumber : contractNubmers) {
                String houseId = map.get(contractNumber);
                if (houseId == null) {
                    completedContracts.add(contractNumber);
                    String sHouseId = houseMap.get(contractNumber);
                    if (StringUtils.isNotBlank(sHouseId)) {
                        houseIds.add(sHouseId);
                    }
                }
            }

            // 更新公租房合同缴费状态
            if (!houseIds.isEmpty()) {
                List<House> houseList = houseRepository.findByIdIn(houseIds);
                houseList.forEach(h -> h.setPaymentStatus(HousePaymentStatusEnum.COMPLETE_PAY.getValue()));
                houseRepository.saveAll(houseList);
            }

            // 更新"已确认待交租"的合同状态
            if (!completedContracts.isEmpty()) {
                List<Contract> contractList = contractRepository
                        .findByStatusAndContractNubmerIn(ContractStatusEnum.WAITING_RENT.getValue(), completedContracts);
                contractList.forEach(c -> c.setStatus(ContractStatusEnum.WAITING_RECORD.getValue()));
                contractRepository.saveAll(contractList);

                Date date = new Date();
                for (String contractNumber : completedContracts) {
                    // 更新租金/押金待办事项状态
                    List<BacklogItemContractBill> contractBill = backlogItemContractBillRepository.findByContractNumber(contractNumber);
                    if (contractBill != null && contractBill.size() > 0) {
                        for (BacklogItemContractBill bill : contractBill) {
                            Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                            if (itemOpt.isPresent()) {
                                BacklogItem item = itemOpt.get();
                                item.setBusinessStatus("已缴费");
                                item.setHandleStatus(1);
                                item.setHandlerTime(date);
                                backlogItemRepository.save(item);
                            }
                        }

                    }
                    // 生成信息备案待提交待办事项
                    Contract contract = contractRepository.findByContractNubmer(contractNumber);
                    if (contract == null) {
                        LOG.error("WxPayService handleAioScanPay<微信一体机扫码账单支付回调> 未找到合同信息, contractNumber={}", contractNumber);
                        return;
                    }

                    AppUser appUsers = null;
                    if (StringUtils.isNotBlank(contract.getMatchUserId())) {
                        appUsers = appUserRepository.findByIdOrEnterpriseUserId(contract.getMatchUserId(), contract.getMatchUserId());

                    }
                    BacklogItem submitItem = new BacklogItem();
                    submitItem.setHouseId(contract.getHouseId());
                    submitItem.setType(BacklogItemTypeEnum.RECORD_SUBMIT.getValue());
                    submitItem.setTitle("公租房信息备案待提交");
                    submitItem.setBusinessStatus("待提交");
                    submitItem.setHandleStatus(0);
                    submitItem.setMatchUserId(contract.getMatchUserId());
                    submitItem.setPhone(appUsers != null ? appUsers.getPhone() : null);
                    submitItem.setCreateTime(new Date());
                    BacklogItem save = backlogItemRepository.save(submitItem);

                    BacklogItemRecordSubmit submit = new BacklogItemRecordSubmit();
                    submit.setBacklogItemId(save.getId());
                    submit.setMatchUserId(contract.getMatchUserId());
                    backlogItemRecordSubmitRepository.save(submit);
                }
            }
        }

        if (!CollectionUtils.isEmpty(rentBills) || !CollectionUtils.isEmpty(expenseBills)) {
            HousePaymentOrder paymentOrder = new HousePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            housePaymentOrderRepository.save(paymentOrder);
        }

        if (!CollectionUtils.isEmpty(estateRentBills) || !CollectionUtils.isEmpty(estateExpenseBills)) {
            EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
            paymentOrder.setBillAmount(billAmount);
            paymentOrder.setOrderNumber(outTradeNo);
            paymentOrder.setPayType(1);
            paymentOrder.setPayMode(redisVo.getPaymentMode());
            paymentOrder.setPayTime(payTime);
            paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
            // 手续费 千分之6
            Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            paymentOrder.setWxCommissionAmount(payHandlingFee);
            paymentOrder.setPayUserId(redisVo.getUserId());
            paymentOrder.setTotalAmount(totalAmount);
            paymentOrder.setPayResult(1);
            estatePaymentOrderRepository.save(paymentOrder);
        }

        SaasHouseWxPay wxpay = new SaasHouseWxPay();
        wxpay.setAppid(result.get("appid"));
        wxpay.setMchId(result.get("mchId"));
        wxpay.setNonceStr(result.get("nonceStr"));
        wxpay.setCreateTime(new Date());
        wxpay.setOrderNumber(result.get("outTradeNo"));
        wxpay.setOutTradeNo(result.get("outTradeNo"));
        wxpay.setPayAmount(Integer.parseInt(result.get("totalFee")));
        wxpay.setPayResultCode(result.get("resultCode"));
        wxpay.setPayReturnCode(result.get("returnMsg"));
        wxpay.setPayStatus(1);
        wxpay.setTransactionId(result.get("transactionId"));
        wxpay.setCallbackTime(DateUtils.convert(result.get("timeEnd"), DateUtils.FORMAT_14));
        saasHouseWxPayRepository.save(wxpay);

        // 提现缓冲期生效 1生效 0不生效
        String bufferStatus = redisService.getValue(Constant.BUFFER_STATUS);
        // 提现缓冲期天数
        String bufferDay = redisService.getValue(Constant.BUFFER_DAY);

        Integer storeType = 2;// 资金存储位置：1企业商户号 2平台商户号
        if (redisVo.getMerchantsType() != null && redisVo.getMerchantsType() == 1) {
            // 收款方式：0平台商户号收款 1企业商户号收款
            storeType = 1;
        }
        // 更新钱包
        aliPayService.updateWallet(redisVo.getOrgId(), storeType, bufferStatus, bufferDay, billAmount, outTradeNo,
                payTime, PaymentTypeEnum.WECHAT.getValue());
    }


    /**
     * 公租房租金待办事项
     *
     * @param ids
     */
    public void rentBillBacklogItem(List<Long> ids) {
        // 获得 租金/押金账单明细表ID， 查找到待办事项表，修改状态
        List<BacklogItemContractBill> contractBill = backlogItemContractBillRepository.findByRentBillIdIn(ids);
        if (contractBill != null && contractBill.size() > 0) {
            Date date = new Date();
            for (BacklogItemContractBill bill : contractBill) {
                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                if (itemOpt.isPresent()) {
                    BacklogItem item = itemOpt.get();
                    item.setBusinessStatus("已缴费");
                    item.setHandleStatus(1);
                    item.setHandlerTime(date);
                    backlogItemRepository.save(item);
                }
            }
        }
    }

    /**
     * 公租房其他费用账单待办事项
     *
     * @param ids
     */
    public void houseOtherBillItem(List<Long> ids) {
        List<BacklogItemHouseOtherBill> houseOtherBill = backlogItemHouseOtherBillRepository.findByBillIdIn(ids);

        if (houseOtherBill != null && houseOtherBill.size() > 0) {
            Date date = new Date();
            for (BacklogItemHouseOtherBill bill : houseOtherBill) {
                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                if (itemOpt.isPresent()) {
                    BacklogItem item = itemOpt.get();
                    item.setBusinessStatus("已缴费");
                    item.setHandleStatus(1);
                    item.setHandlerTime(date);
                    backlogItemRepository.save(item);
                }
            }
        }
    }

    /**
     * 非公租房租金待办事项
     *
     * @param ids
     */
    public void propertyRentItem(List<Long> ids) {
        List<BacklogItemPropertyRentBill> propertyRentBill = backlogItemPropertyRentBillRepository.findByRentBillIdInOrDepositBillIdIn(ids, ids);
        if (propertyRentBill != null && propertyRentBill.size() > 0) {
            Date date = new Date();
            for (BacklogItemPropertyRentBill bill : propertyRentBill) {
                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                if (itemOpt.isPresent()) {
                    BacklogItem item = itemOpt.get();
                    item.setBusinessStatus("已缴费");
                    item.setHandleStatus(1);
                    item.setHandlerTime(date);
                    backlogItemRepository.save(item);
                }
            }
        }
    }


    /**
     * 非公租房其他账单待办事项
     *
     * @param ids
     */
    public void propertyOtherItem(List<Long> ids) {
        List<BacklogItemPropertyOtherBill> propertyOtherBill = backlogItemPropertyOtherBillRepository.findByBillIdIn(ids);
        if (propertyOtherBill != null && propertyOtherBill.size() > 0) {
            Date date = new Date();
            for (BacklogItemPropertyOtherBill bill : propertyOtherBill) {
                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                if (itemOpt.isPresent()) {
                    BacklogItem item = itemOpt.get();
                    item.setBusinessStatus("已缴费");
                    item.setHandleStatus(1);
                    item.setHandlerTime(date);
                    backlogItemRepository.save(item);
                }
            }
        }

    }

    /*
     *分转换为元
     */
    private String fenToYuan(String amount) {
        NumberFormat format = NumberFormat.getInstance();
        try {
            Number number = format.parse(amount);
            double temp = number.doubleValue() / 100.0;
            format.setGroupingUsed(false);
            // 设置返回的小数部分所允许的最大位数
            format.setMaximumFractionDigits(2);
            amount = format.format(temp);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return amount;
    }

}
